2017-05-24 70 views
0

我正在通過swift3中的故事板在uitableview中實現長按。故事板中只有一個原型單元格。但問題是長按僅在第一個單元中被檢測到。其餘的單元沒有聽到長按手勢。UILongPressGestureRecognizer在表格視圖單元格中使用時出現問題

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 10 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
     let row = indexPath.row 
     cell.textLabel?.text = "Label" 

     return cell 
} 

    @IBAction func longPress(_ guesture: UILongPressGestureRecognizer) { 

     if guesture.state == UIGestureRecognizerState.began { 
      print("Long Press") 
     } 
    } 

控制檯中顯示的警告是:

的時間,這是絕對不允許,現在執行。從iOS 9.0開始,它將被放入第一個被加載到的視圖中。

+0

您將手勢附加到哪個視圖? –

+0

uitableview cell –

+1

只需將longpressgesture添加到整個tabelview –

回答

1

您需要在添加的cellForRowAtIndexPath手勢所有細胞

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
     let row = indexPath.row 
     cell.textLabel?.text = "Label" 

     let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(HomeViewController.longPress(_:))) 
     cell?.addGestureRecognizer(longPressRecognizer) 
     return cell 
} 



func longPress(_ guesture: UILongPressGestureRecognizer) { 

     if guesture.state == UIGestureRecognizerState.began { 
      print("Long Press") 
     } 
    } 
+0

爲什麼向下投票? – KKRocks

+0

您不應該爲每個單元附加一個手勢。最好創建一個gestureRecongnizer並放在tableview上。請參閱https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/IncorporatingGestureSupport/IncorporatingGestureSupport.html「UICollectionView類是UIScrollView的後代,因此將您的手勢識別器附加到集合視圖的可能性較小來干擾必須跟蹤的其他手勢。「 –

1

連接的手勢的實現代碼如下,當手勢被觸發弄清楚這indexPath選擇。

override func viewDidLoad() { 
    super.viewDidLoad() 
     let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(_:))) 
    tableView?.addGestureRecognizer(longPressRecognizer) 
} 

func longPress(_ guesture: UILongPressGestureRecognizer) { 

    if guesture.state == UIGestureRecognizerState.began { 
     let point = guesture.location(in: tableView) 
     let indexPath = tableView.indexPathForRow(at: point); 
     print("Long Press \(String(describing: indexPath))") 
    } 
} 

因爲tableview中是一種滾動型的,最好的姿態連接到的tableview本身,而不是它的任何子視圖。這樣就不太可能干擾必須跟蹤的其他手勢。

相關問題