Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView and touchesBegan / touchesEnded etc

I have a UIView with 2 subviews, let's call it view A:

  • a basic UIView, called B
  • a 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?

like image 687
MartinMoizard Avatar asked Mar 05 '15 08:03

MartinMoizard


2 Answers

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 ")

}
like image 189
Lilo Avatar answered Oct 12 '22 04:10

Lilo


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.

like image 20
Anushka Madushan Avatar answered Oct 12 '22 06:10

Anushka Madushan