Arsen Magendov
Arsen Magendov

Reputation: 37

Two actions for tap in tableview

Two actions for tap in tableview!

I have a question about tapping in tableview. Can I set secondary action on tap ? 1. tap (default). 2. I tap and hold the selected cell for 2-3 seconds and an alternative action is performed.

Upvotes: 3

Views: 234

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

You can, you need to add a UILongPressGestureRecognizer in your cell.contentView and handle that event, your 1 event "Normal Tap event" will be triggered by didSelectRowAtIndexPath default method while the hold event will be triggered by the UILongPressGestureRecognizer

Example of cell implementation

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
    }

}

TableView DataSource && Delegate example implementation

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")
    }
}

Upvotes: 5

Related Questions