Reputation: 59
I currently have a custom type Cell that I use to populate cells info, style, etc... with. Here's the code
struct Cell {
var opened = Bool()
var isChecked = Bool()
var body = String()
var icon = UIImage()
var cellStyle: UITableViewCell.CellStyle?
var detailTextLabel: String?
var accessoryType: UITableViewCell.AccessoryType?
var action: CellDelegate?
}
I would like to add a property that contains a specific method for each cell. Most solutions I came across suggest using cell's tag and go from there but I can't imagine this being a sustainable solution. Most of those functions are literally to transition from one view to the other i.e. push views. The rest are used to toggle switches, update texts, etc... I'm also open to other ideas on how I can do this. Thanks
Edit: don't get distracted by CellDelegate type, it was basically one of my attempts in trying to get this to work
Upvotes: 0
Views: 134
Reputation: 9915
If your method has always the same signature then:
Swift solution:
add a property to the Cell
var action: (() -> Void)?
Objective-C solution:
add a property to the Cell with selector
var action: Selector? // action = #selector(customMethod) and cell perform a selector
If a method signature varies then you can use Any type
var action: Any?
and cell which calls the action must know the signature. This is done with casting:
class CellView: UITableViewCell {
private var cell: Cell!
fun configureWith(_ cell: Cell) {
self.cell = cell
}
override func select(_ sender: Any?) {
if let action = cell.action as? (String) -> Int {
action()
}
}
}
Upvotes: 1