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

给cell添加手势,不少人一看以为这不简单:bash

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

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

那若是咱们须要在tableViewController里面给每一个cell添加手势呢? 可能有些人又会说,直接在cellforrow里面 addGestureRecognizer 不就能够了。spa

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

正确姿式:

以在每一个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…教程

相关文章
相关标签/搜索