在tableview中点击两个动作

Ars*_*dov 3 uitableview ios swift swift4

在tableview中点击两个动作!

我有一个关于在tableview中点击的问题.我可以设置次要操作吗?1.点击(默认).2.点击并按住所选单元格2-3秒,然后执行替代操作.

Rei*_*ian 5

你可以,你需要添加一个UILongPressGestureRecognizer在您cell.contentView和处理该事件,您的1个事件"正常敲击事件"将被触发didSelectRowAtIndexPath默认的方法,同时按住事件将被触发UILongPressGestureRecognizer

单元实现的示例

import UIKit

class LongPressTableViewCell: UITableViewCell {

    var longPressGesture : UILongPressGestureRecognizer?
    var longPressClosure : (()->Void)?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func setupWithClosure(closure:@escaping (()->Void)) {
        self.longPressClosure = closure
        if(longPressGesture == nil) {
            longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:)))
            longPressGesture!.minimumPressDuration = 2
            self.contentView.addGestureRecognizer(longPressGesture!)
        }
    }



    @objc func longPressAction(gesture:UILongPressGestureRecognizer) {
        if (gesture.state == UIGestureRecognizerState.began){
                self.longPressClosure?()
        }
     }


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
Run Code Online (Sandbox Code Playgroud)

TableView DataSource &&委托示例实现

extension ViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "LongPressTableViewCell", for: indexPath) as? LongPressTableViewCell{
            cell.setupWithClosure {
                //LongPress action
                debugPrint("LongPress")
            }
            return cell
        }

        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        debugPrint("Tap Action")
    }
}
Run Code Online (Sandbox Code Playgroud)