Add UITapGestureRecognizer to UITextView without blocking textView touches
To do that make your view controller adopt to UIGestureRecognizerDelegate and override should recognize simultaneously with gesture recognizer method like:
override func viewDidLoad() { tapTerm = UITapGestureRecognizer(target: self, action: "tapTextView:") tapTerm.delegate = self textView.addGestureRecognizer(tapTerm)}func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true}
In case anyone came here looking for @Zell B.'s answer in Objective C, here's the code:
- (void)viewDidLoad { [super viewDidLoad]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textViewTapped:)]; tap.delegate = self; tap.numberOfTapsRequired = 1; [self.textView addGestureRecognizer:tap];} - (void)textViewTapped:(UITapGestureRecognizer *)tap { //DO SOMTHING }#pragma mark - Gesture recognizer delegate- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; }
PS: Don't forget < UIGestureRecognizerDelegate >
Swift 4.2
The following steps allows me to escape a full-screen UITextView with a tap, whilst allowing to scroll the contents of the UITextView:
- Disconnected the UIGestureRecognizer from the UITableView.
- Made a CustomTextView: UITextView.
- Added a 'sender' var to the particular UIViewController with the CustomTextView.
- Trap for 'Touches Ended...'
- Call for an excape function within the sender UIViewController.
class CustomTextView: UITextView { var sender: DocViewController? override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let controller = sender { controller.handleSwipeGesture() } }}
I can either scroll the contents of the UITextView or merely tap to exit.
The 'sender' is set from the hosting UIViewController at creation.