I have a UIView
with 2 subviews, let's call it view A
:
UIView
, called B
UIScrollView
, called C
I overrided the following method in view A
:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
When I touch view B
, touchesBegan:withEvent:
and touchesEnded:withEvent:
get called, but if I touch the UIScrollView
(view C
), there are not called.
I know this is the expected behaviour, but I am trying to understand why. I could not find any clear answer on that. Any idea?
Use the TapGestureRecognizer instead of touchBegan method
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
singleTapGestureRecognizer.numberOfTapsRequired = 1;
singleTapGestureRecognizer.enabled = YES;
singleTapGestureRecognizer.cancelsTouchesInView = NO;
[scrollView addGestureRecognizer:singleTapGestureRecognizer];
- (void)singleTap:(UITapGestureRecognizer *)gesture {
//handle taps
}
Swift version :
let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTap:")
singleTapGestureRecognizer.numberOfTapsRequired = 1
singleTapGestureRecognizer.enabled = true
singleTapGestureRecognizer.cancelsTouchesInView = false
scrollViewH.addGestureRecognizer(singleTapGestureRecognizer)
func singleTap(sender: UITapGestureRecognizer) {
println("handle taps ")
}
if you have scroll view thouchesBegan method will not work because if want scrolling you have to Enable userInteractionEnabled to YES in storyboard. If you make it to NO it'll trigger. So solution is use TapGestureRecognizer Add this to your viewDidLoad:
let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: "MyTapMethod:")
singleTapGestureRecognizer.numberOfTapsRequired = 1
singleTapGestureRecognizer.enabled = true
singleTapGestureRecognizer.cancelsTouchesInView = false
myscrollView.addGestureRecognizer(singleTapGestureRecognizer)
Then add this MyTapMethod in your controller.
func MyTapMethod(sender: UITapGestureRecognizer) {
//NSLog("touchesBegan")
self.view.endEditing(true)
}
This is working fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With