我有一个表格视图,用于配置一个单元(来自VC),
cell.model = dataSource[indexpath.row]
在cell.model的didSet中,我正在初始化单元格内容。Cell有3个按钮,点击它们,我通过CellDelegate通知VC
protocol CellDelegate {
func didTapButton1(model: Model)
func didTapButton2(model: Model)
func didTapButton3(model: Model)
}
我的关注:-我不想在这里传递模型(因为它已经与Cell关联-以某种方式需要从Cell中获取模型)我想不带参数调用didTapButton()。然后在VC中,
extension VC: CellDelegate {
//I need to fetch the model associated with the cell.
func didTapButton1() { }
func didTapButton2() { }
func didTapButton3() { }
}
我可以使用闭包来实现这一点,但是在这里不是首选。任何帮助将不胜感激。*
我猜测您不希望通过模型的原因是,在所有三种方法中都具有一个model
看起来像代码重复。好吧,如果您查看框架中的委托,例如UITableViewDelegate
,UITextFieldDelegate
,则大多数(如果不是全部)都接受作为第一个参数的委托。 UITableViewDelegate
中的所有方法都有一个tableView
参数。因此,也可以遵循该模式:
protocol CellDelegate {
func didTapButton1(_ cell: Cell)
func didTapButton2(_ cell: Cell)
func didTapButton3(_ cell: Cell)
}
个人,我将只在此委托中编写一种方法:
protocol CellDelegate {
func didTapButton(_ cell: Cell, buttonNumber: Int)
}
在VC扩展中,您只需检查buttonNumber
即可查看按下了哪个按钮:
switch buttonNumber {
case 1: button1Tapped()
case 2: button2Tapped()
case 3: button3Tapped()
default: fatalError()
}
// ...
func button1Tapped() { ... }
func button2Tapped() { ... }
func button3Tapped() { ... }