protocol CellConfigurator {
var cellClass: UICollectionViewCell.Type {get}
func configure(cell: UICollectionViewCell)
}
class AppleCell: UICollectionViewCell {
let title = UILabel()
}
class AppleCellConfigurator: CellConfigurator {
let cellClass: UICollectionViewCell.Type = AppleCell.self
func configure(cell: UICollectionViewCell) {
guard let cell = cell as? AppleCell else {return}
cell.title.text = "AAPL"
}
}
UICollectionViewCell
,请按如下方式使用(伪代码):
func cellAt(indexPath: IndexPath) -> UICollectionViewCell {
let configurator = configurators[indexPath]
let cell = collectionView.dequeueReusableCell(identifier: String(describing: configurator.cellClass))
configurator.configure(cell)
return cell
}
我期待着摆脱在每一个符合
CellConfigurator
protocol CellConfigurator {
associatedtype Cell
func configure(cell: Cell)
}
class AppleCell: UICollectionViewCell {
let title = UILabel()
}
class AppleCellConfigurator: CellConfigurator {
typealias Cell = AppleCell
func configure(cell: Cell) {
cell.title.text = "AAPL"
}
}
但是,由于一个错误,我无法将它们组合在一个数组中:“协议‘SomeProtocol’只能用作泛型约束,因为它具有自身或关联的类型需求”。
有没有办法实现这两个目标:
-
有功能的
UICollectionViewCell
任何
细胞配置器
-
在一个特定的配置器的功能中有一个具体的类型