要在集合视图中使用单元格中的按钮删除项,你需要执行以下步骤:
target
和action
正确设置。deleteItems(at:)
方法更新集合视图。performBatchUpdates(_:completion:)
进行动画处理,保持流畅的用户体验。class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var items = ["Item 1", "Item 2", "Item 3"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
let deleteButton = UIButton(type: .system)
deleteButton.setTitle("Delete", for: .normal)
deleteButton.addTarget(self, action: #selector(deleteItem(_:)), for: .touchUpInside)
cell.contentView.addSubview(deleteButton)
// 设置按钮布局约束
return cell
}
@objc func deleteItem(_ sender: UIButton) {
guard let indexPath = collectionView.indexPath(for: sender.superview?.superview as! UICollectionViewCell) else { return }
items.remove(at: indexPath.item)
collectionView.deleteItems(at: [indexPath])
}
}
通过以上步骤,你可以在集合视图的单元格中添加删除按钮,并实现删除功能。
领取专属 10元无门槛券
手把手带您无忧上云