2015-11-09 158 views
0

當我點擊一個單元格時,我想要接收特定於該單元格的索引或其他標識符。代碼工作並進入輕擊功能。但是,我怎樣才能得到一個索引或類似的東西?點擊單元格並獲得索引

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ShowCell", forIndexPath: indexPath) as UICollectionViewCell 

    if cell.gestureRecognizers?.count == nil { 
     let tap = UITapGestureRecognizer(target: self, action: "tapped:") 
     tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)] 
     cell.addGestureRecognizer(tap) 
    } 

    return cell 
} 

func tapped(sender: UITapGestureRecognizer) { 
    print("tap") 
} 
+0

有一個解決您的確切問題在這裏:http://stackoverflow.com/a/34899415/5815633 – Uriel

回答

0

想一想。 sender是輕拍手勢識別器。 g.r.的view是這個單元格。現在您可以向收集視圖詢問該單元的索引路徑是什麼(indexPathForCell:)。對馬茨

enter image description here

+0

你可以讓我喜歡你所有的動作。我的回答是正確的。 – matt

+1

是不是像sender.view和比? – da1lbi3

+0

添加了一個截屏視頻,顯示它的工作原理。 – matt

0

構建回答

首先,我們添加自來水識別

let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapped(tapGestureRecognizer:))) 
cell.textView.addGestureRecognizer(tap) 

然後,我們用下面的函數來獲得indexPath

@objc func tapped(tapGestureRecognizer: UITapGestureRecognizer){ 
    //textField or what ever view you decide to have the tap recogniser on 
    if let textField = tapGestureRecognizer.view as? UITextField { 

     // get the cell from the textfields superview.superview 
     // textField.superView would return the content view within the cell 
     if let cell = textField.superview?.superview as? UITableViewCell{ 

      // tableview we defined either in storyboard or globally at top of the class 

      guard let indexPath = self.tableView.indexPath(for: cell) else {return} 
      print("index path =\(indexPath)") 

// then finally if you wanted to pass the indexPath to the main tableView Delegate 

       self.tableView(self.tableView, didSelectRowAt: indexPath) 

      } 
    } 
} 
相關問題