从单元格委托中删除重复代码代码
removing the duplicating code code from cell delegate
我有一个表视图,用于配置单元格(来自 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() { ... }
我有一个表视图,用于配置单元格(来自 VC),
cell.model = dataSource[indexpath.row]
在cell.model的didSet中,我正在初始化单元格内容。 Cell 有 3 个按钮,点击它们,我通过 CellDelegate
通知 VCprotocol 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() { ... }