我有一个 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
}
}
最佳答案
直接编辑单元格的框架可能不是最好的方法。而是覆盖collectionView sizeForItemAtIndexPath
,并在那里指定高度变化。这应该允许 Collection View 使用新的单元格高度正确地重新布局。
您可以查看其他问题,例如 this欲了解更多详情,请点击此处
关于swift - 当我使用按钮增加单元格高度时,UICollectionView 单元格彼此重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57778212/