2017-05-24 71 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本身,而不是它的任何子视图。这样就不太可能干扰必须跟踪的其他手势。

相关问题