Reputation: 7047
I have a TableView with a custom cell that requires rather lengthy configuration and is used more than once in my app. I would like to avoid duplicated code and just configure the cell in one place. Can I create a function like this?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "betterPostCell", for: indexPath) as! BetterPostCell
return configureCell(cell)
}
Ideally, I would be able to put configureCell
in my BetterPostCell class. Is this possible?
Upvotes: 0
Views: 724
Reputation: 91
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
}
Upvotes: 0
Reputation: 3235
Yes, you can do it, and it's a nice way to keep your table view code from blowing up, especially if you have many different types of cells in one table view.
In your BetterPostCell class, create a method called configure like so:
func configure() {
//configure your cell
}
Then in your cellForRowAt method, just call that method from your cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "betterPostCell", for: indexPath) as! BetterPostCell
cell.configure()
return cell
}
Upvotes: 2
Reputation: 2766
You can create a protocol with a configure
function and associated type Cell
. Using protocol extensions, you can add default implementations for different cell types, and additional methods.
protocol CellConfigurable {
associatedType Cell
func configure(_ cell: Cell)
}
extension CellConfigurable where Cell == SomeTableViewCell {
func configure(_ cell: SomeTableViewCell) {
...
}
}
Upvotes: 1