【iOS12+Swift5+Xcode10进阶知识】如何在tableViewController里面给tableViewCell添加手势

495 阅读1分钟

给cell添加手势,很多人一看觉得这不简单:

1.直接在自定义的cell的class里面 addGestureRecognizer

2.stroyboard上面直接拖个手势控件给原型cell

那如果我们需要在tableViewController里面给每个cell添加手势呢? 可能有些人又会说,直接在cellforrow里面 addGestureRecognizer 不就可以了。

这样的话只能给第一个cell添加手势。

正确姿势:

以在每个cell上面添加swipe轻扫手势为例:

class TableViewController: UITableViewController, UIGestureRecognizerDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let swipe = UIGestureRecognizer(target: self, action: #selector(handleSwipe(swipe:)))
        tableView.addGestureRecognizer(swipe)
        swipe.delegate = self
        
    }
    
    @objc func handleSwipe(swipe: UISwipeGestureRecognizer){
        if swipe.state == .ended{
            let swipeLocation = swipe.location(in: tableView)
            if let swipeIndexPath = tableView.indexPathForRow(at: swipeLocation),
              let swipeCell = tableView.cellForRow(at: swipeIndexPath) as? MyTableViewCell{
                //有了indexPath和cell就可以做任何事啦!
            }
        }
    }
}

这只是本人觉得最简单最容易的理解的一个方法,大家如果有别的方法的话,希望不吝赐教。

广告时间:

本人目前专职在做一些iOS的视频教程,可以免费试听一部分,大家如果觉得好的话希望多多支持: m.cctalk.com/inst/s9vfhe…