Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

ios - Swift - add gesture recognizer to object in table cell

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!
                }
            }
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...