ios - 启用分页时 UICollectionView 使隐藏单元出列

标签 ios swift uicollectionview

启用分页后,UICollectionView 仅使 3 个单元格出列,其余单元格无缘无故地因隐藏而出列。也许,这是 UICollectionView 一般的工作方式,但在我的项目中,我确实需要每次将单元格出队时 cellForItemAt indexPath: IndexPath method 被调用,它实际上会创建自定义 UICollectionViewCell 的非隐藏实例。

也许,它只创建了3个实例,因为它需要正确管理内存。但是,在我的项目中,自定义 UICollectionViewCell 还包含另一个 collectionView,它由 3 个自定义 collectionView 单元格组成。这些collectionView单元格内部还有tableViews,其数据封装在这些单元格中。我的主要问题是:为什么 UICollectionView 在我的例子中只创建 3 个实例,我该如何避免这种行为?

我的实际项目中的层次结构如下所示: UICollectionView -> UICollectionView -> 3 个自定义 UICollectionViewCell -> 每个 UICollectionViewCell 包含一个 tableView -> 每个 tableView 包含一个特定的自定义 TableViewCell

这是我编写的完整代码,作为实际项目中发生的情况的示例(这不是实际项目,但行为是相同的):

ViewController:

class ViewController: UIViewController {

    let cellId = "uniqueCellId"
    let sampleWords: [String] = ["one", "two", "three", "four", "five", "six"]
    let colors: [UIColor] = [.green, .yellow, .blue, .purple, .gray, .red]

    override func viewDidLoad() {
        super.viewDidLoad()
        registerCollectionViewCustomCell()
        prepareUI()
        setupViews()
        setCollectionViewLayoutToHorizontal()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //collectionView is instantiated as a computed property. Initialized with a system flow layout. The frame is initially assigned to CGRect.zero because it is controlled by the constrains
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.layer.cornerRadius = 8
        cv.isPagingEnabled = true
        cv.delegate = self
        cv.dataSource = self
        return cv
    }()
}

扩展1

extension ViewController {
    private func prepareUI() {
        view.backgroundColor = UIColor.black
        navigationController?.navigationBar.barTintColor = .white
        navigationItem.title = "Collection View"
    }

    private func registerCollectionViewCustomCell() {
        collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    }

    private func setCollectionViewLayoutToHorizontal() {
        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }
    }

    private func setupViews() {
        view.addSubview(collectionView)

        view.addConstraintsWithFormat(format: "H:|-15-[v0]-15-|", views: collectionView)
        view.addConstraintsWithFormat(format: "V:|-80-[v0]-140-|", views: collectionView)

    }
}

扩展2:

//configuring the dataSource and the delegate methods for the collectionView
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CustomCollectionViewCell
        cell.backgroundColor = colors[indexPath.item]
        cell.wordLabel.text = sampleWords[indexPath.item]
        print("_____________________________________")
        print(cell.isHidden)
        if cell.isHidden {
            print("CUSTOM CELL INSTANCE NOT CREATED")
        }
        print("_____________________________________")
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sampleWords.count
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size = CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
        return size
    }
}

CustomCollectionViewCell 类:

//custom cell class
class CustomCollectionViewCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        print("instance of CustomCollectionViewCell is created")
    }

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

    let wordLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private func setupViews() {
        addSubview(wordLabel)

        wordLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        addConstraint(NSLayoutConstraint(item: wordLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 70))
    }
}

帮助方法addConstraintsWithFormat:

//helper method to add constraints to a view
extension UIView {
    func addConstraintsWithFormat(format: String, views: UIView...){
        var viewsDictionary = [String : UIView]()
        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view
        }

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}

这是我拥有的所有代码。一切都是在没有 Storyboard的情况下仅以编程方式完成的。

为了调试并了解自己发生了什么,我添加了一些打印语句: 1) “Print”语句,如果单元格被隐藏,并且 cell.isHidden -> true -> 尚未创建自定义 CollectionViewCell 实例,则输出 bool 值。 2) 在 init 方法的自定义 CollectionViewCell 类中使用“Print”语句来查看是否已创建单元格。

输出始终如下:

instance of CustomCollectionViewCell is created
______________________________________
false
______________________________________
instance of CustomCollectionViewCell is created
______________________________________
false
______________________________________
instance of CustomCollectionViewCell is created
______________________________________
false
______________________________________
______________________________________
true
CUSTOM CELL INSTANCE NOT CREATED

之后 cell.Hidden 始终返回真值。

我发现有些人也遇到了同样的问题。但解决方案对我没有帮助。因为我不在任何地方使用方法 collectionView.reloadData() 并且我无法更改单个单元格的大小。 UICollectionViewCell gets hidden randomly

最佳答案

UICollectionView 将立即在屏幕上可见的单元格出列,并以 isHidden = false 的形式将其出列,并以 isHidden = true 的形式将正在准备的屏幕外的其他单元格出列。这反射(reflect)了当您查看显示时这些单元格的实际状态。您无法通过设置 hidden = false 来覆盖此行为或 isHidden 的状态。当单元格滚动进入和退出 View 时,UICollectionView 会自动更新此状态。

我实现了类似的结构,其中 UICollectionViewCell 包含另一个 UICollectionView。 (一个在该单元格内水平滚动,第二个在该单元格内垂直滚动。)我可以明确指出,UICollectionView 单元格没有必要使用 isHidden = false 来正确布局单元格的 subview 。听起来你可能认为这个隐藏的属性是你遇到问题的原因(我一直沿着这条确切的思维路径),但你实际上错了,问题的原因是其他的。

就我而言,根据记录,问题单元格报告自动布局约束冲突,我一直忽略它,因为我认为它不相关。解决方法是,在将 subview 添加到 UICollectionViewCell 后,我需要在单元 View 上调用 layoutSubviews() ,并在其包含的 Collection View 上调用 reloadData() 。如果我不这样做,嵌入的集合有时会起作用,但是当它重新使用以前创建的单元格而不是创建新的单元格时,它们将由于自动布局冲突而无法显示。这意味着存在到达那里的特定路径,这些路径会或不会显示问题,具体取决于在可重用的先前 View 中创建的单元格。

关于ios - 启用分页时 UICollectionView 使隐藏单元出列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48926506/

相关文章:

swift - 更改所选 UICollectionView 单元格的大小

json - 在 Swift 中动态解码任意 json 字段

ios - Firebase 交易 - 这是正确的吗?

ios - 按钮点击事件不触发

ios - 过渡到具有透明背景图像的 UINavigationBar 会导致黑色闪烁

iOS UICollectionview 渲染背景颜色错误

swift - UICollectionView ScrollTo 崩溃

ios - UIImagePickerController 在打开相机时崩溃

ios - Parse - 如何将两部分查询变成单个查询?

ios - 为什么元素会无缘无故停止显示?