2017-08-30 54 views
0

我有一個自定義單元格的TableView需要相當長的配置,並在我的應用程序中多次使用。我想避免重複的代碼,並在一個地方配置單元格。我可以創建一個這樣的功能嗎?在TableView之外配置自定義TableViewCell?

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

     return configureCell(cell) 
} 

理想情況下,我就可以把configureCell我BetterPostCell類。這可能嗎?

+0

裏面的你'BetterPostCell' class add'configure (withItem item:T)'你可以調用cell.configure(withItem:_item)並返回單元格 – Lamar

回答

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 
}