You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移除字符串复用标识符遇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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:32:52