[英]If specific CollectionViewCell is clicked do something
我試圖弄清楚如何對我的 collectionView 進行編程以檢測被點擊的單元格,然后我想使用 if 方法為每個單元格做一些不同的事情。
這樣做時:
@objc func tap(_ sender: UITapGestureRecognizer) {
let location = sender.location(in: self.collectionView)
let indexPath = self.collectionView.indexPathForItem(at: location)
if let index = indexPath {
print("Got clicked on index: \(index)!")
}
例如,我的調試器說:當我點擊第 3 號單元格時,點擊了索引:[0, 3]。我想要完成的是,例如,如果點擊了第 3 號單元格,請執行一些操作。 以及所有其他單元格的不同操作。
例如,我嘗試了不同的方法,例如
if indexPath?.section == 3 {
NSLog("Tapped 3")
}
但沒有運氣。 可能是一種簡單的方法,但我對編程很陌生,在其他帖子或視頻上沒有找到任何幫助。
您不需要手動處理點擊事件。 使用此 function 獲取單元格點擊事件。
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) {
//print(indexPath.row) // this print 2 when you click on 3rd cell(because indexes starting from 0)
if indexPath.row == 2{
//the action you want to do when 3rd cell click
}
// do something you want
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.