【问题标题】:UICollectionView Cells overlapping with each other when i use a button to increase cell height当我使用按钮增加单元格高度时,UICollectionView 单元格相互重叠
【发布时间】:2019-09-03 20:15:48
【问题描述】:

我有一个 CollectionView 设置,里面有一个按钮,可以将单元格高度增加一个固定量。但是,当它这样做时,它会与下面的单元格重叠,这意味着下面的单元格不会向下移动以腾出空间。

这几天我一直在尝试解决这个问题,但我似乎无法让它发挥作用。

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var colors = [UIColor.red,UIColor.blue]
    @IBOutlet weak var col: UICollectionView!

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cellCollectionViewCell
        cell.frame.size.height = CGFloat(317 + cell.button.tag*45)
        cell.backgroundColor = colors[indexPath.row]
        return cell
    }

    @IBAction func increaseHeight(_ sender: Any) {
        col.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

class cellCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var butt: UIButton!
    @IBAction func incHeight(_ sender: UIButton) {
        sender.tag = sender.tag + 1
    }
}


【问题讨论】:

    标签: swift xcode uicollectionview


    【解决方案1】:

    直接编辑单元格的框架可能不是最好的方法。而是覆盖collectionView sizeForItemAtIndexPath,并在那里指定高度变化。这应该允许集合视图使用新的单元格高度正确重新布局。

    您可以查看其他问题,例如this 以了解更多详情

    【讨论】:

    • 嗯,我似乎无法让它工作,因为我无法从该方法内部访问 cell.button,或者至少我不知道如何
    • 你可以做UICollectionView.cellForIndexPath
    猜你喜欢
    • 2013-10-30
    • 2018-09-13
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2017-06-23
    • 1970-01-01
    • 2015-08-06
    相关资源
    最近更新 更多