Swift中如何给函数传递动态类型参数,实现多Cell配置逻辑复用?
解决方案
你可以通过协议抽象的方式实现类型安全的复用,这是最优实现方案,步骤如下:
步骤1:定义公共属性协议
把函数中用到的cellBGView、titleLabel两个属性声明为协议要求,协议约束遵守者必须是UICollectionViewCell的子类:
protocol TopCellConfigurable: UICollectionViewCell { var cellBGView: UIView? { get } var titleLabel: UILabel? { get } }
步骤2:让需要复用的Cell类遵守协议
所有要使用这个函数的UICollectionViewCell子类,只需要声明遵守上述协议即可,不需要额外实现代码(只要原有类已经包含对应属性):
// 原有Cell遵守协议 extension SearchExploreCollectionViewCell: TopCellConfigurable {} // 其他需要复用的Cell也遵守协议 extension YourOtherCollectionViewCell: TopCellConfigurable {}
步骤3:修改原函数入参类型
把原函数的入参类型替换为协议类型,原有逻辑完全不需要改动:
func unselectedTopCell(cell: TopCellConfigurable) { let color = UIColor(named: "textBlack") ?? .black let borderColor = color.withAlphaComponent(0.12) let textColor = color.withAlphaComponent(0.87) cell.cellBGView?.borderColor = borderColor cell.cellBGView?.borderWidth1 = 1 cell.titleLabel?.textColor = textColor }
调用方式
直接传入任意遵守TopCellConfigurable协议的Cell实例即可:
// 原有调用逻辑不变 unselectedTopCell(cell: searchExploreCell) // 新的Cell类型也可以直接传入 unselectedTopCell(cell: yourOtherCell)
备选方案(不推荐)
如果你不想新增协议,也可以用泛型+KVC的方式实现,但是这种方式没有编译时检查,属性名拼写错误会导致运行时崩溃:
func unselectedTopCell<T: UICollectionViewCell>(cell: T) { let color = UIColor(named: "textBlack") ?? .black let borderColor = color.withAlphaComponent(0.12) let textColor = color.withAlphaComponent(0.87) if let bgView = cell.value(forKey: "cellBGView") as? UIView { bgView.borderColor = borderColor bgView.setValue(1, forKey: "borderWidth1") } if let titleLabel = cell.value(forKey: "titleLabel") as? UILabel { titleLabel.textColor = textColor } }
内容的提问来源于stack exchange,提问作者user10469417
相关产品推荐
相关产品推荐

