拆分代理协议后,如何设置Cell的delegate属性类型?
解决方案
针对你拆分协议后Cell代理类型的问题,有两种实用方案,都能保证协议方法的强制实现(无需依赖协议扩展的默认实现):
方案一:拆分两个独立的代理属性
将Cell的代理拆分为两个对应不同协议的可选属性,让不同的实现类按需设置:
class Cell: UITableViewCell { // 对应基础操作的代理 weak var actionDelegate: CellActionHandling? // 对应非活跃视图操作的代理 weak var notActiveActionDelegate: NotActiveViewActionHandling? // 触发对应操作时调用 func handleNotActiveStateChange(_ state: Cell.State) { notActiveActionDelegate?.notActiveViewAction(state: state) } func handleOptionButtonTap() { actionDelegate?.didTapOptionButton() } func handleEditButtonTap() { actionDelegate?.didTapEditButton() } }
- 仅需实现基础操作的类,只需设置
actionDelegate; - 需要实现全部操作的类,同时设置
actionDelegate和notActiveActionDelegate; - 优势:职责划分清晰,调用时无需类型转换,代码直观。
方案二:保留单个代理,调用时做类型判断
保留原来的单个代理属性,类型为基础协议CellActionHandling,在需要调用拆分出的方法时,判断代理是否遵循NotActiveViewActionHandling协议:
// 可选:定义组合协议,方便同时遵循两个协议的类声明 protocol FullCellActionHandling: CellActionHandling, NotActiveViewActionHandling {} class Cell: UITableViewCell { weak var delegate: CellActionHandling? func handleNotActiveStateChange(_ state: Cell.State) { // 通过类型转换调用对应方法 (delegate as? NotActiveViewActionHandling)?.notActiveViewAction(state: state) } func handleOptionButtonTap() { delegate?.didTapOptionButton() } func handleEditButtonTap() { delegate?.didTapEditButton() } }
- 仅需基础操作的类,直接遵循
CellActionHandling并设置为delegate; - 需要全部操作的类,遵循
FullCellActionHandling(或同时遵循两个协议),设置为delegate后,类型转换会自动生效; - 优势:保持了原有代理的结构,改动较小,无需新增属性。
两种方案都能确保协议方法的强制实现——因为没有使用协议扩展提供默认实现,遵循协议的类必须实现对应方法,符合你的需求。
内容的提问来源于stack exchange,提问作者mjh
相关产品推荐
相关产品推荐

