swift - UICollectionViewCell 委托不会触发
问题描述
我显然做错了什么,但还不能确定在哪里。我将单元格设置如下:
protocol PropertyPhotoCellDelegate: class {
func deletePropertyPhoto(cell: PropertyPhotoCell)
}
class PropertyPhotoCell: UICollectionViewCell {
weak var propertyPhotoCellDelegate: PropertyPhotoCellDelegate?
let deleteButton: UIButton = {
let button = UIButton()
let image = UIImage(named: "delete.png")
button.setImage(image, for: .normal)
button.showsTouchWhenHighlighted = true
button.isHidden = true
button.addTarget(self, action: #selector(handleDeleteButton), for: .touchUpInside)
return button
}()
var isEditing: Bool = false {
didSet {
deleteButton.isHidden = !isEditing
}
}
我省略了设置单元格视图。这是选择器
@objc fileprivate func handleDeleteButton() {
propertyPhotoCellDelegate?.deletePropertyPhoto(cell: self)
}
在 UICollectionViewController 中,我分配了委托
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! PropertyPhotoCell
cell.photoImageView.image = photos[indexPath.item]
cell.propertyPhotoCellDelegate = self
return cell
}
这将隐藏或显示单元格上所有视图中的单元格的删除按钮
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
navigationItem.rightBarButtonItem?.isEnabled = !editing
if let indexPaths = collectionView?.indexPathsForVisibleItems {
for indexPath in indexPaths {
if let cell = collectionView?.cellForItem(at: indexPath) as? PropertyPhotoCell {
cell.deleteButton.isHidden = !isEditing
}
}
}
}
最后,符合这里的协议
extension PropertyPhotosController: PropertyPhotoCellDelegate {
func deletePropertyPhoto(cell: PropertyPhotoCell) {
if let indexPath = collectionView?.indexPath(for: cell) {
photos.remove(at: indexPath.item)
collectionView?.deleteItems(at: [indexPath])
}
}
}
我点击UICollectionViewController
Edit
按钮,所有单元格都按预期显示删除按钮。任何单元格的delete
按钮都会在点击时突出显示,但我没有看到delegate
被调用。
解决方案
在 UICollectionViewController 中分配委托时,还要为单元格设置选择器。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! PropertyPhotoCell
cell.photoImageView.image = photos[indexPath.item]
cell.propertyPhotoCellDelegate = self
cell.deleteButton.addTarget(cell, action: #selector(cell.handleDeleteButton), for: .touchUpInside)
cell.deleteButton.isHidden = true
return cell
}
推荐阅读
- spring-boot - 禁用不需要的 OAuth 端点 spring boot
- reactjs - 如何在我的反应组件中添加验证消息
- vba - For-Next 循环没有停止
- ios - Swift ios 从视图中切出圆角矩形,允许颜色变化
- sapui5 - 带有文本换行的 sap.ui.table.table(渲染问题)
- typescript - 在 Typescript 中将静态转换为动态导入
- reactjs - 编辑使用“yarn build”构建的 reactapp 结果中的字符串而不重建
- javascript - 在带有 ion-item 的 NTH 元素之后添加项目
- html - 将进度条引导程序 4(居中值)与按钮对齐
- rust - 夜间使用 rust 时无法安装 xargo -“属性中的非字符串文字或顶级位置的字符串文字是实验性的”