这种方法删除了随机单元格,但不是我想要的单元格。我认为问题在于使用indexPath初始化按钮,我不知道如何修复它。
如果我没弄错,indexPath.item表示UICollectionView中的一行。那么bug在哪里?
extension UIButton {
struct Holder {
static var _myComputedProperty:IndexPath!
}
var indexPath:IndexPath {
get {
return Holder._myComputedProperty
}
set(newValue) {
Holder._myComputedProperty = newValue
}
}
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrRequest.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! RequestCell
cell.delete.indexPath = indexPath
cell.delete.addTarget(nil, action: #selector(del(sender:)), for: .touchUpInside)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 235)
}
@objc func del(sender: UIButton) {
arrRequest.remove(at: sender.indexPath.item)
self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [sender.indexPath])
}) { (finished) in
self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems)
}
}
答案 0 :(得分:0)
请更改您的代码,如下所示
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! RequestCell
cell.delete.tag = index path.row
cell.delete.addTarget(nil, action: #selector(del(sender:)), for: .touchUpInside)
return cell
}
您的删除方法如下:
@objc func del(sender: UIButton) {
let indexPath = IndexPath(item: sender.tag, section: 0)
arrRequest.remove(at: indexPath)
self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [indexPath])
}) { (finished) in
self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems)
}
}