2017-08-30 92 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 
}