我正在使用自定义类CollectionViewConfigurator
以通用方式处理CollectionViewCell的配置。
它运行良好,这是示例类:
protocol ConfigurableCell {
static var reuseIdentifier: String { get }
associatedtype DataType
func configure(data: DataType)
}
extension ConfigurableCell {
static var reuseIdentifier: String { return String(describing: Self.self) }
}
protocol CellConfigurator {
static var reuseId: String { get }
func configure(cell: UIView)
var hash: Int { get }
}
class CollectionViewCellConfigurator<CellType: ConfigurableCell, DataType: Hashable>: CellConfigurator where CellType.DataType == DataType, CellType: UICollectionViewCell {
static var reuseId: String { return CellType.reuseIdentifier }
let item: DataType
init(item: DataType) {
self.item = item
}
func configure(cell: UIView) {
(cell as! CellType).configure(data: item)
}
var hash: Int {
return String(describing: CellType.self).hashValue ^ item.hashValue
}
}
extension Int: Diffable {
public var diffIdentifier: AnyHashable {
return self
}
}
注意:我受到一篇很好的文章的启发,该文章演示了
UITableView
的相同用法。我在UICollectionView
上尝试过,这太棒了。无论如何,我想在此
UICollectionView
中处理拖放。为此,如果我正确理解了委托方法,则UICollectionView中的项目必须符合
NSItemProviderWriting
和NSItemProviderReading
协议。当我添加协议方法时,这是错误:
泛型类型不支持静态存储的属性
然后,我阅读此post以了解错误并尝试绕过此错误。
但是恐怕我正在深入研究该语言的一个非常复杂的领域。
有人可以解释我如何使用泛型在我的课堂上遵守那些协议吗?
最佳答案
链接的文章是特例。通常,您不需要做太多的事情就可以得到想要做的事情。唯一的问题是您不能使用存储的属性。您必须使用计算的属性。因此,举例来说,如果您要执行此操作(存储的属性):
static let writableTypeIdentifiersForItemProvider = ["public.url"]
您只需要这样做(等效的计算属性):
static var writableTypeIdentifiersForItemProvider: [String] { return ["public.url"] }
链接的文章解决了您需要属性可写的情况,这意味着您需要为其提供存储,但这是一种罕见的情况。
实际上,如果您希望
CellConfigurator
符合NSItemProviderWriting
,则它看起来像:protocol CellConfigurator: NSItemProviderWriting { ... }
然后
CollectionViewCellConfigurator
需要从NSObject
继承(以获取NSObjectProtocol
):class CollectionViewCellConfigurator<CellType: ConfigurableCell, DataType: Hashable>: NSObject ...
这意味着
hash
需要添加override
:override var hash: Int { ... }
最后,您将实现
NSItemProviderWriting
方法:static var writableTypeIdentifiersForItemProvider: [String] { return [...] }
func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping (Data?, Error?) -> Void) -> Progress? {
// ...
}
(其中
...
是您想要的此类型)NSItemProviderReading
使用相同的过程。