首页 > 解决方案 > Swift 4.2 使用 UICollectionViewCell 添加/删除按钮

问题描述

当按下按钮(在 之外)时,我试图UIButton在我的每个单元格中添加一个,然后在没有按下时将其删除。UICollectionViewUICollectionView

基本上,boolean如果为真 - 显示/添加,否则隐藏/删除。这是我的cellForItemAt。我也尝试将其添加到willDisplay cell.

let btnItemDelete = UIButton()
btnItemDelete.tag = indexPath.row
btnItemDelete.addTarget(self, action: #selector(self.btnItemDeleteClick), for: .touchUpInside) //Selector works
btnItemDelete.frame = CGRect(x: cell.bounds.width-22, y: 2, width: 20, height: 20) //Creation works
btnItemDelete.setImage(deleteImage, for: .normal) //Image works



if (isEdit) {
    //Add or Show
    cell.addSubview(btnItemDelete)
}
else {
    //Delete or Hide
    btnItemDelete.removeFromSuperview()
}

运行时,isEdit最初设置为 false 并且按钮不显示。单击按钮更改布尔值后,将出现按钮。当单击按钮将布尔值设置回 false 时,按钮会保留。我认为它与btnItemDelete.removeFromSuperview()- 是否有不同的方法来做到这一点?我想我不能隐藏/显示它们,因为它只会在每次重新加载时继续向单元格添加一个新按钮。

标签: iosswiftuicollectionviewuibuttonuicollectionviewcell

解决方案


首先你需要添加到

cell.contentView不是cell

这样

btnItemDelete.removeFromSuperview()

您即时删除未添加的按钮,而是需要

cell.contentView.subviews.forEach {
  if $0.tag == 12 {
     $0.removeFromSuperview()
   }
}

我认为最好的方法是在单元格布局上添加按钮,然后管理它的外观

cell.myButton.isHidden = !isEdit

推荐阅读