[英]selector for button inside collectionView cell
這讓我瘋了,我已經讀了好幾個小時並試了一切,不能讓這個按鈕選擇器工作。 這應該不難。
在CellForItemAt內部我設置了按鈕標簽並嘗試調用按鈕。
cell.deleteCellButton.tag = indexPath.item
cell.deleteCellButton.addTarget(self, action: #selector(deleteCellButtonTapped(sender:)), for: UIControlEvents.touchUpInside)
我試過(_ :),“deleteCellButtonTapped:”,以及任何其他數量的括號組合,我仍然得到無法識別的選擇器。 我不知道為什么autocomplete建議(發送者:)我以前從未見過這個。
然后我的按鈕功能:
func deleteCellButtonTapped(sender: UIButton!) {
self.packArray.remove(at: sender.tag)
print(packArray.count)
self.outerCollectionView.deleteItems(at: [IndexPath(item: sender.tag, section: 0)])
self.outerCollectionView.reloadData()
self.outerCollectionView.layoutIfNeeded()
}
假設您正在使用Swift 3,並且func deleteCellButtonTapped(sender: UIButton!)
位於同一個類中:
addTarget(self, action: #selector(deleteCellButtonTapped(sender:)), for: .touchUpInside)
工作正常。
從它的類中引用選擇器方法對我有用。
你可以做的是訪問選擇器方法前綴為它的類名 。
我假設你的類名是MyClassViewController
。 你的代碼看起來像:
class MyClassViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
.... // Other implementation methods
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
....// create cell object and dequeue
cell.deleteCellButton.addTarget(self, action: #selector(MyClassViewController.deleteCellButtonTapped(_:)), for: .touchUpInside)
return cell
}
func deleteCellButtonTapped(_ sender: Any) {
// your method implementation
print("Selector method called")
}
}
希望這很好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.