ios - Swift 4.2 使用 UICollectionViewCell 添加/删除按钮
问题描述
当按下按钮(在 之外)时,我试图UIButton
在我的每个单元格中添加一个,然后在没有按下时将其删除。UICollectionView
UICollectionView
基本上,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()
- 是否有不同的方法来做到这一点?我想我不能隐藏/显示它们,因为它只会在每次重新加载时继续向单元格添加一个新按钮。
解决方案
首先你需要添加到
cell.contentView
不是cell
这样
btnItemDelete.removeFromSuperview()
您即时删除未添加的按钮,而是需要
cell.contentView.subviews.forEach {
if $0.tag == 12 {
$0.removeFromSuperview()
}
}
我认为最好的方法是在单元格布局上添加按钮,然后管理它的外观
cell.myButton.isHidden = !isEdit
推荐阅读
- r - 带有长表达式的 R 正则表达式
- google-chrome - 有没有办法将伪元素“之前”/“之后”直接添加到 Chrome 的开发工具样式选项卡?
- node.js - Nestjs招摇问题
- sql - Hibernate 无法从终端执行可以正常执行的查询
- java - 为 kafka connect s3 sink 连接器定义自定义格式
- mysql - MYSQL SELECT 时间戳为 1 到 2 周的所有行
- mallet - Mallet:“VM 初始化期间发生错误。无法为 3145728KB 对象堆预留足够的空间?
- php - WooCommerce:显示产品变体/变量描述
- javascript - 在 Promise.All 中释放 MySQL 连接
- api - 在 AWS 实例上查询 Elasticsearch