Search code examples
iosswiftuitableviewbuttonstoryboard

How to create a long press button in TableView Cell to segue


I can only create my segue function from the ViewController and I must have the longPress functions in my TableViewCell. There's no way to make reference to the segue function without getting an error. How would I implement this code in the cellForRow to segue when the button is held within the TableView Cell? By the way, I'm using a storyboard.

@objc func longPress(gesture: UILongPressGestureRecognizer) {
        if gesture.state == UIGestureRecognizer.State.began {
            print("Long Press")
            //performSegue(withIdentifier: "toProfile", sender: self)
        }
      }

    func addLongPressGesture(){
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
            longPress.minimumPressDuration = 0.75
            self.expandButton.addGestureRecognizer(longPress)

Solution

  • I found an easy yet unorthodox solution but works like a charm:

    Place a second button into your TableView Cell, connect your segue, and set it to hidden. Then create your IBOutlet for it, which I named SegueButton:

    @IBOutlet weak var LongPressButton: UIButton!
    @IBOutlet weak var SegueButton: UIButton!
    

    Now add to your awakeFromNib:

    override func awakeFromNib() {
    addLongPressGesture()
    }
    

    Lastly, add the long press button code:

    @objc func longPress(gesture: UILongPressGestureRecognizer) {
                if gesture.state == UIGestureRecognizer.State.began {
                    print("Segue was Successful")
                    SegueButton.sendActions(for: .touchUpInside)
                    }
                }
    
        func addLongPressGesture(){
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
            longPress.minimumPressDuration = 0.75
            self.LongPressButton.addGestureRecognizer(longPress)
        }
    }