【发布时间】:2020-07-12 15:25:05
【问题描述】:
我已经定义了一个协议如下:
protocol CustomCell where Self: UICollectionViewCell {
associatedType Config
var cellConfiguration: Config!
func setup(with configuration: Config)
}
然后我有一个自定义 UICollectionViewCell:
class RedCollectionViewCell: UICollectionViewCell, CustomCell {
var cellConfiguration: RedCollectionViewCellConfiguration!
func setup(with configuration: Config) {
...
}
...awakeFromNib and other functions...
}
RedCollectionViewCellConfiguration 的定义位置:
class RedCollectionViewCellConfiguration: NSCoding {
...
}
最终目标是拥有许多不同的自定义 UICollectionViewCell,它们都符合 CustomCell,每个都定义自己的自定义配置类(因为每种类型的自定义集合视图单元格将需要不同的配置,因为它们将包含不同类型的数据) .我计划将单元配置存储在 Core Data 中,然后在 ViewController.collectionView(_:cellForItemAt:) 中检索它。在ViewController.collectionView(_:cellForItemAt:) 我正在尝试这样做:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
if let cell = cell as? CustomCell {
cell.setup(tile,with: configuration)
}
由于情绪低落,我收到以下错误: Protocol 'CustomCell' 只能用作通用约束,因为它具有 Self 或关联的类型要求
我在 Stack Overflow 上看到过其他答案,但没有任何帮助。有没有替代方法来解决这个问题?我考虑过在 CustomCell 中不包括 associatedType 和 cellConfiguration,但如果所有符合条件的类型都有一个唯一的配置类,那将是理想的。
【问题讨论】:
标签: ios swift protocols associated-types typecasting-operator