【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…教程

相關文章
相關標籤/搜索