2015-08-29 157 views
8

我正在嘗試將手勢識別器添加到表格視圖單元格中的對象(特定圖像)。現在,我對手勢識別器很熟悉,但對於如何設置這一點我們還是有點困惑。實際的表格單元格沒有viewDidLoad方法,所以我不認爲我可以在那裏聲明手勢識別器。Swift - 將手勢識別器添加到表格單元格中的對象

這個問題(UIGestureRecognizer and UITableViewCell issue)似乎是相關的,但答案是在客觀的C,不幸的是我只能流利的迅速。

如果有人可以幫我解釋如何在表格單元格中添加一個手勢識別器(不是整個tableview)的對象,甚至可能幫助我將上述鏈接的答案翻譯成迅速,我會很感激

回答

15

這裏的鏈接後的解決方案的快速斯威夫特翻譯,增加了滑動手勢識別到的UITableView,然後確定刷卡發生哪些細胞上:

class MyViewController: UITableViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     var recognizer = UISwipeGestureRecognizer(target: self, action: "didSwipe") 
     self.tableView.addGestureRecognizer(recognizer) 
    } 

    func didSwipe(recognizer: UIGestureRecognizer) { 
     if recognizer.state == UIGestureRecognizerState.Ended { 
      let swipeLocation = recognizer.locationInView(self.tableView) 
      if let swipedIndexPath = tableView.indexPathForRowAtPoint(swipeLocation) { 
       if let swipedCell = self.tableView.cellForRowAtIndexPath(swipedIndexPath) { 
        // Swipe happened. Do stuff! 
       } 
      } 
     } 
    } 

} 
+0

雖然這兩個答案都是正確的,但我選擇了這個,因爲它更完整。非常感謝 :) –

2

在這裏你去。你在你的問題

「而不是直接添加手勢識別到細胞中提到的解決方案的斯威夫特版本,你可以在viewDidLoad中把它添加到tableview中。

在didSwipe法,您可以確定受影響IndexPath和細胞如下:」

func didSwipe(gestureRecognizer:UIGestureRecognizer) { 
    if gestureRecognizer.state == UIGestureRecognizerState.Ended { 
     let swipeLocation = gestureRecognizer.locationInView(self.tableView) 
      if let swipedIndexPath = self.tableView.indexPathForRowAtPoint(swipeLocation){ 
      if let swipedCell = self.tableView.cellForRowAtIndexPath(swipedIndexPath!){ 


     } 
    } 
    } 
} 
相關問題