Darrrky89
Darrrky89

Reputation: 141

Get touchesBegan on a subview (UIWebView)

I've an UIWebView which is added as a subview in a UIview and I would like to detect when this UIWebView is touched but touchesBegan just don't work.

Any idea ?

Upvotes: 3

Views: 3962

Answers (3)

dvdblk
dvdblk

Reputation: 2905

Swift 5

subview.swift

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    self.next?.touchesBegan(touches, with: event)
}

If you're unsure if you should call super.touchesBegan(touches, with: event), refer to the doc discussion.

superview.swift

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // handle
}

Upvotes: 0

Nir Golan
Nir Golan

Reputation: 1336

Subclassing and waiting for touchesBegan won't help you, as it won't get called.
I subclassed UIWebView and just "leeched" onto its gesture recognizers in subviews 2 levels deep (you could go recursively but thats enough for iOS6-7). Then you can do whatever you want with the touch location and gesture recognizer's state.

for (UIView* view in self.subviews) {
    for (UIGestureRecognizer* recognizer in view.gestureRecognizers) {
        [recognizer addTarget:self action:@selector(touchEvent:)];
    }
    for (UIView* sview in view.subviews) {
        for (UIGestureRecognizer* recognizer in sview.gestureRecognizers) {
            [recognizer addTarget:self action:@selector(touchEvent:)];
        }
    }
}

Upvotes: 0

greenhorn
greenhorn

Reputation: 1107

  1. Subclass UIWebView in your code and then implement touchesBegan in your class.
  2. Add the subclassed webview as a subview of your UIView.
  3. Call super in the subclassed UIWebView

    - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    {
        [super touchesBegan: touches withEvent: event];
    }
    

Upvotes: 3

Related Questions