移除字符串复用标识符遇AnyClass问题:如何优化UICollectionView复用逻辑?
关于UICollectionView复用Cell的协议封装问题
使用字符串作为Cell复用标识符容易引发问题,我通过协议实现了复用标识符的自动生成方案:
protocol ReuseIdentifiable { static var reuseIdentifier: String { get } } extension ReuseIdentifiable { static var reuseIdentifier: String { String(describing: Self.self) } } extension UICollectionViewCell: ReuseIdentifiable {} extension UITableViewCell: ReuseIdentifiable {}
该方案可正常运行,示例代码如下:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: GroupsViewCell.reuseIdentifier, for: indexPath ) return cell } override func viewDidLoad() { super.viewDidLoad() collectionView.register( GroupsViewCell.self, forCellWithReuseIdentifier: GroupsViewCell.reuseIdentifier ) collectionView.delegate = self collectionView.dataSource = self collectionLayout.layoutItems(in: self.collectionView) }
但尝试进一步封装UICollectionView的方法,让其仅接收Cell类即可完成注册和复用操作时,register方法出现错误:
extension UICollectionView { // Error: no exact matches in call to instance method 'register'... func register(_ cellClass: ReuseIdentifiable) { register( cellClass.self, forCellWithReuseIdentifier: type(of: cellClass).reuseIdentifier ) } // 此方法正常运行 func dequeueReusableCell(_ ofType: ReuseIdentifiable, for indexPath: IndexPath) -> UICollectionViewCell { return dequeueReusableCell( withReuseIdentifier: type(of: ofType).reuseIdentifier, for: indexPath) } }
苹果文档提到:
The protocol to which all class types IMPLICITLY conform.
我明白ReuseIdentifiable协议与AnyClass并非同一概念,尝试让协议继承AnyClass时:
protocol ReuseIdentifiable: AnyClass { // code here }
出现错误:
Inheritance from non-protocol, non-class type 'AnyClass' (aka 'any AnyObject.Type')
请问如何正确将cellClass传递给UICollectionView的register方法?毕竟直接传递GroupsViewCell.self的方式在原有代码中是可行的。
内容的提问来源于stack exchange,提问作者Alexey_BH
相关产品推荐
相关产品推荐

