swift - 当我使用按钮增加单元格高度时,UICollectionView 单元格彼此重叠

标签 swift xcode uicollectionview

我有一个 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
    }
}


enter image description here enter image description here

enter image description here

最佳答案

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

您可以查看其他问题,例如 this欲了解更多详情,请点击此处

关于swift - 当我使用按钮增加单元格高度时,UICollectionView 单元格彼此重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57778212/

相关文章:

ios - 在 Swift 中调整 UICollectionViewCell 的大小时出错

ios - UICollectionView 未显示以查看

ios - 无法在 Swift 的 ViewController 类中创建子类的对象

swift - 如何设置圆的物理属性使其遵循给定路径

ios - UITableView 设置不同的图片

ios - 如何以编程方式使用 SWIFT 根据其中 UIlabel 的动态大小设置 UICollectionViewCell 大小?

ios - 缩小图像复制到粘贴板后变得模糊 - Swift 3.0

html - 如何将 html 文本设置为标签 Swift

Swift 4 - 将数据传递到 Collection View 单元中嵌入的 TableView

ios - 自动签名无法解决 "WebDriverAgentRunner"目标的权利问题