【问题标题】:Subclass of UICollectionViewCell Subclass that is initialized from a XIB fileUICollectionViewCell 的子类 从 XIB 文件初始化的子类
【发布时间】:2021-12-14 17:05:16
【问题描述】:
class BaseUICollectionViewCell: UICollectionViewCell { // -> This comes from XIB 
    func method() {}
} 

class SubClassUICollectionViewCell: BaseUICollectionViewCell { // -> Overrides some of its super class methods
    override func method() {}
} 

如何在我的收藏视图中同时使用它们?

在您回答之前,请确保您创建了一个项目并测试我在这里解释的内容!我需要针对此处提到的当前案例的解决方案!

class ViewController: UIViewController {
    @IBOutlet var collectionView: UICollectionView!

    public override func viewDidLoad() {
        super.viewDidLoad()
        collectionViewSetup()
    }

    private func collectionViewSetup() {
        collectionView.delegate = self
        collectionView.dataSource = self

        // What is the right thing overe here
        let xib = UINib(nibName: "BaseUICollectionViewCell", bundle: Bundle(for: Self.self))
        collectionView.register(xib, forCellWithReuseIdentifier: "BaseUICollectionViewCell")}
    }
}

// MARK: - UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // what is the right thing over here
        if indexPath.row %2 == 0 {
            // BaseUICollectionViewCell
        } else {
            // SubClassUICollectionViewCell
        }
        return UICollectionViewCell()
    }
}

【问题讨论】:

    标签: swift uicollectionview uicollectionviewcell xib


    【解决方案1】:

    您完全正确,这是一个问题。就好像基于 xib 的设计过程是继承概念的敌人。

    我认为你有三个选择:

    • 在两个单独的 xib 文件中设计相同的东西两次。这样,从笔尖出来的细胞类别从一开始就是正确的。您可能会讨厌这个,因为它非常不干燥(一直到“这是一场维护噩梦”),但正如我认为您已经直觉的那样,这就是您让自己进入的方式,代码/类的方式结构已经写好了。

    • 不要使用单元格 xib。像 Big Boys 那样用代码设计整个事情(真正的程序员不使用 Interface Builder);这样,类继承完全对您有利。或者,如果您真的想在 Interface Builder 中进行设计,请设计一个普通视图:在代码中,将其从 nib 中取出,放入单元格的内容视图中,然后手动连接所有内容(出口和操作等)。

    • 不要使用类继承,而是使用依赖注入。无论您的两个“类”之间需要不同的逻辑是什么,都将体现在一个基于类继承的 helper 对象中,该对象可以注入到 same 单元类中.

    我最喜欢第三个。但是,您认为您需要在单元格中任何“不同”代码的事实本身可能是一种不好的气味,因为单元格是视图,不应该做任何“思考”。我把这个想法留给你。

    【讨论】:

    • 非常感谢......我希望有更好的方法来做到这一点,但我认为它们都有优点和缺点......对于第一个选项它是可能的,但可能不是东西,不值得。对于第二个选项,我讨厌这个,因为很难用协议和视图模型样式来告诉第三个选项的可视化实现这就是我正在做的:)
    猜你喜欢
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2011-01-15
    • 2015-12-26
    • 1970-01-01
    相关资源
    最近更新 更多