我正在尝试将手势识别器添加到表格视图单元格中的对象(具体地说,是图像)。现在,我熟悉了手势识别器,但对于如何设置它,我感到有点困惑。实际的表单元格没有viewDidLoad方法,所以我不认为我可以在那里声明手势识别器。
这个问题(UIGestureRecognizer and UITableViewCell issue )似乎是相关的,然而答案在目标C中,不幸的是我只会说swift。
如果有人能帮我把手势识别器添加到表格单元格中的对象(而不是整个表视图),或者甚至可以帮助我将上面的链接翻译成swift,我将不胜感激
发布于 2015-08-30 05:00:14
这里是链接帖子解决方案的快速翻译,将滑动手势识别器添加到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!
}
}
}
}
}发布于 2015-08-30 04:58:35
这就是你要的。您在问题中提到的解决方案的快速版本
“您可以将其添加到viewDidLoad的表视图中,而不是直接将手势识别器添加到单元格中。
在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!){
}
}
}
}发布于 2018-07-22 09:51:31
Swift 4的更新:
let swipeGestueRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(didRecognizeSwipeGestue(_:)))
self.view.addGestureRecognizer(swipeGestueRecognizer)和选择器:
@objc func didRecognizeSwipeGestue(_ sender: UISwipeGestureRecognizer) {
if sender.state == UIGestureRecognizerState.ended {
let location = sender.location(in: self.tableView)
if let indexPath = tableView.indexPathForRow(at: location) {
if let cell = self.tableView.cellForRow(at: indexPath) {
// todo
}
}
}
}https://stackoverflow.com/questions/32290126
复制相似问题