我显然在做错事,但到目前为止还无法确定在哪里。我将单元格设置如下:
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
被调用。
答案 0 :(得分:0)
在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
}