2017-08-30 12 views
0

かなり長時間の設定が必要なカスタムセルを持つTableViewがあり、アプリケーションで複数回使用されています。重複したコードを避け、1つの場所でセルを設定したいと思います。このような関数を作成できますか?TableViewの外にカスタムTableViewCellを設定しますか?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "betterPostCell", for: indexPath) as! BetterPostCell 

     return configureCell(cell) 
} 

理想的には、私は私のBetterPostCellクラスでconfigureCellを置くことができるだろう。これは可能ですか?

+0

を'BetterPostCell'クラスが' configure (withItem item:T) 'を追加すると、cell.configure(withItem:_item)を呼び出してセルを返します – Lamar

答えて

1

はい、あなたはそれを行うことができ、そしてそれはあなたが1つのテーブルビューのセルの多くの異なる種類を持っている場合は特に、爆破からあなたのテーブルビューのコードを維持するための良い方法です。あなたのBetterPostCellクラスで

、そのように構成するというメソッドを作成します。

func configure() { 
    //configure your cell 
} 

を次に、あなたのcellForRowAt方法では、ちょうどあなたのセルからそのメソッドを呼び出します。あなたの内部

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "betterPostCell", for: indexPath) as! BetterPostCell 
     cell.configure() 
     return cell 
} 
0

configure関数と関連するタイプCellを使用してプロトコルを作成できます。プロトコル拡張を使用すると、さまざまなセルタイプと追加メソッドのデフォルトの実装を追加できます。

protocol CellConfigurable { 
    associatedType Cell 

    func configure(_ cell: Cell) 
} 

extension CellConfigurable where Cell == SomeTableViewCell { 

    func configure(_ cell: SomeTableViewCell) { 
     ... 
    } 
} 
0
try this code to create CustomCell:- 

class CustomCell: UITableViewCell { 

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
     super.init(style: style, reuseIdentifier: reuseIdentifier) 
     self.initViews() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     self.perform(#selector(self.initViews), with: self, afterDelay: 0) 
    } 

    //MARK: Init views 
    func initViews() { 
     //Add your code 
    } 

    //MARK: Layout subviews 

    override func layoutSubviews() { 
     super.layoutSubviews() 
    // Here you can code for layout subviews 
    } 

    //MARK: Update all valuesw model 

    func updateWithModel(_ model: AnyObject) { 
    //here you can update values for cell 
    } 

} 


//Call CustomCell in Tableview class 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell 
     cell.updateWithModel(items[indexPath.row]) 
     return cell 
} 
関連する問題