【问题标题】:removing the duplicating code code from cell delegate从单元委托中删除重复的代码代码
【发布时间】:2020-02-26 13:44:24
【问题描述】:

我有一个表格视图,用于配置一个单元格(来自 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)
}

我的担心:- 我不想在这里传递模型(因为它已经与单元相关联 - 不知何故需要从单元中获取模型) 我想在没有参数的情况下调用 didTapButton() 。然后在VC里面,

extension VC: CellDelegate {
//I need to fetch the model associated with the cell.
    func didTapButton1() { }
    func didTapButton2() { }
    func didTapButton3() { }
}

我可以使用闭包来实现这一点,但这里不是首选。 任何帮助将不胜感激。*

【问题讨论】:

  • 为什么不想传递模型参数?委托中只有一个函数 - didTapButton(model:buttonNumber:) 怎么样?

标签: swift generics delegates delegation redundancy


【解决方案1】:

我猜你不想通过模型的原因是因为在所有三种方法中都有一个model 看起来像代码重复。好吧,如果您查看框架中的委托,例如UITableViewDelegateUITextFieldDelegate,那么大多数(如果不是全部)都接受他们作为委托的第一个参数。 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可能有2个tableview,为了区分delegate在delegate中有tableview参数
  • 我仍然没有得到支持点,为什么我们必须发送参数? - 苹果框架有原因,但我们为什么要这样做?
  • @Nagaraj 你想要这个模型吗?拥有一个单元格参数可以让您获得模型。
猜你喜欢
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2021-09-11
相关资源
最近更新 更多