Swift - 将手势识别器添加到表格单元格中的对象 [英] Swift - add gesture recognizer to object in table cell
问题描述
我正在尝试向表格视图单元格中的对象(特别是图像)添加手势识别器。现在,我对手势识别器很熟悉,但是对于如何设置这个问题我感到有些困惑。实际的表格单元格没有viewDidLoad方法,所以我认为我不能在那里声明手势识别器。
I'm attempting to add a gesture recognizer to an object (an image, specifically) in a table view cell. Now, I'm familiar with gesture recognizers, but am left slightly confused as to how to set this up. The actual table cell doesn't have a viewDidLoad method, so I don't think I can declare the gesture recognizer there.
这个问题( UIGestureRecognizer和UITableViewCell问题)似乎是相关的,但答案是在客观C中,不幸的是我只是流利的。
This question (UIGestureRecognizer and UITableViewCell issue ) seems to be related, however the answer is in objective C, and unfortunately I'm only fluent in swift.
如果有人可以帮我解决如何向表格单元格中的对象添加手势识别器(不是整个桌面视图),甚至可能帮助我将上述链接的答案翻译成swift,我将不胜感激
If anybody could perhaps help me out on how I'd go about adding a gesture recognizer to an object in a table cell (NOT the whole tableview), or even perhaps aid me in translating the answer from the above link to swift, I'd be grateful
推荐答案
这里是一个快速的Swift翻译链接帖子的解决方案,将滑动手势识别器添加到UITableView,然后确定滑动发生在哪个单元格:
Here's a quick Swift-translation of the linked post's solution, adding the swipe gesture recognizer to the UITableView and then determining which cell the swipe happened on:
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!
}
}
}
}
}
这篇关于Swift - 将手势识别器添加到表格单元格中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!