Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow UIScrollView to scroll when UIButton is pressed

I have a UIView inside a UIScrollView, inside the UIView is a button. The issue is that when I press that button, hold it, (in this case the button state is pressed) and try to scroll, my scroll view doesn't scroll. In which it should. The UIView has a gesture recognizer in it and I am trying to use one of it's delegate to allow the scroll view to be scrolled if I have my hands pressed the UIButton and scroll. How do I do this?

Basically to summarize, I need to pass the touch event to the scroll view if the button is pressed/hold. If it's a touch up event from the button then clearly it should trigger the action of the button and not scroll.

like image 521
xonegirlz Avatar asked Feb 20 '23 20:02

xonegirlz


2 Answers

Old question, but I just had this issue and thought people would benefit from the answer. If you have a UIControl inside a UIScrollView, by default the scroll won't cancel the touch event. The solution is to subclass the UIScrollView like this:

@implementation PaginationScrollView {}

- (id)init {
    self = [super init];
    if (self) {
        self.canCancelContentTouches = YES;
    }
    return self;
}

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
    return YES;
}

@end

the default implementation of touchesShouldCancelInContentView returns NO if the view is a UIControl.

like image 126
Eduardo Scoz Avatar answered Feb 22 '23 09:02

Eduardo Scoz


Make sure setting

yourScrollView.canCancelContentTouches = YES;

Still not working? Because it only cancels touches instead of UIControlEvents such as UIControlEventTouchUpInside

How to solve? Add this to the top of your .m file

@implementation UIScrollView (TouchesShouldCancelInContentView)

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
    return YES;
}

@end
like image 44
Tim Chen Avatar answered Feb 22 '23 09:02

Tim Chen