我在 UICollectionViewController 中的单元格消失了

My cells in the UICollectionViewController disappear

我创建了一个 TableViewController 并在其上创建了一个 header。我在 header 中添加了一个 UICollectionViewController。当我点击细胞时,它们正在消失。有人遇到同样的问题吗?

import UIKit
class HeaderController {

override init(frame: CGRect) {
super.init(frame: frame)

let categoryCollectionController = CategoryCollectionController(collectionViewLayout: UICollectionViewFlowLayout())
let categoryView = categoryCollectionController.view!
categoryView.translatesAutoresizingMaskIntoConstraints = false
addSubview(categoryView)

NSLayoutConstraint.activate([
categoryView.leftAnchor.constraint(equalTo: leftAnchor),
categoryView.rightAnchor.constraint(equalTo: rightAnchor),
categoryView.topAnchor.constraint(equalTo: topAnchor),
categoryView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
}
}



class CategoryCollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let cellID = "UID"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.backgroundColor = .red
        collectionView.register(CellCategory.self, forCellWithReuseIdentifier: cellID)
        if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CellCategory
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
}

您可以通过在 header 上保留对 collection 视图的引用来解决此问题。

如果不保留对 collection 视图的引用(并且不仅仅是您添加为子视图的弱视图 属性),它会在 init 退出后被丢弃范围。

例如:


class HeaderController: UIView {

    let categoryCollectionController = CategoryCollectionController(collectionViewLayout: UICollectionViewFlowLayout())

    override init(frame: CGRect) {
        super.init(frame: frame)

        let categoryView = categoryCollectionController.view!
        categoryView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(categoryView)

        NSLayoutConstraint.activate([
            categoryView.leftAnchor.constraint(equalTo: leftAnchor),
            categoryView.rightAnchor.constraint(equalTo: rightAnchor),
            categoryView.topAnchor.constraint(equalTo: topAnchor),
            categoryView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}