2
votes

Is it possible to implement a long press gesture on a UITextView? Basically, if the user tap once on a textview I want him/her to be able to edit the text. However, if he/she tap and hold on the textview (let's say for two seconds) an action will be performed? If the answer is yes please give me direction on how this could be achieved?

Follows is the solution for my problem as per kchromik's asnwer:

(1) First step is define the following extension before the ViewController Class begins:

extension ViewController: UIGestureRecognizerDelegate { func gestureRecognizer (_ gestureRecognizer: UIGestureRecognizer, shouldRecognizerSimultaneouslyWithotherGestureRecognizer: UIGestureRecognizer) -> Bool { return true}}

(2) Second step is to link the UITextView Outlet from the Main Storyboard to the swift code file:

@IBOutlet weak var testTextView: UITextView!

(3) Third step is to drag and drop a GestureRecognizer from the Object Library on top of the UITextView you want to implement a Longpress Gesture Recognizer on.

(4) The Fourth step is add the below code under viewDidLoad () {

    let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))

    uilpgr.minimumPressDuration = 2

    testTextView.addGestureRecognizer(uilpgr)

uiplgr.delegate = self

}

(5) The last step is to define the function to be used with the Longpress Gesture Recognizer defined earlier on:

func longpress(gestureRecognizer: UIGestureRecognizer) {

    print("Long tap") // Execute what you want to do

}
1
Update your question with what you have tried so far. Clearly explain what issues you are having. - rmaddy
Your code is about adding a gesture to a label, not a text view. You should fix your question. - rmaddy

1 Answers

0
votes

By default a UILabel has user interactions disabled. Try testLabel.isUserInteractionEnabled = true in your viewDidLoad or enable it in the storyboard:

enter image description here

UPDATE

If you UIView has it's own gesture recogniser, you can implement following delegate:

extension ViewController: UIGestureRecognizerDelegate {
  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
  }
}

And you don't forget to set uilpgr.delegate = self