lunadiviner
lunadiviner

Reputation: 509

How to allow swiping over UIButtons to scroll?

I have a carousel menu of UIButtons in my app. Everything works great except that the buttons are kinda big and it won't scroll when a finger is dragged across the button. The dragging has to be done outside of the button that's currently front and center in the carousel. Is there some setting I can change so that I can swipe across the buttons to scroll and have them also be interactable?

Here's the code that creates the buttons:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 500.0f, 320.0f);
button.layer.cornerRadius = 8.0f;
button.layer.masksToBounds = NO;
button.layer.borderWidth = 0.0f;

button.layer.shadowColor = [UIColor blackColor].CGColor;
button.layer.shadowOpacity = 0.8;
button.layer.shadowRadius = 12;
button.layer.shadowOffset = CGSizeMake(12.0f, 12.0f);

[button setImage:(UIImage*)[buttons objectAtIndex:index] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

Upvotes: 1

Views: 619

Answers (1)

Rafał Sroka
Rafał Sroka

Reputation: 40030

Make sure UIScrollView property canCancelContentTouches is set to YES.

scrollView.canCancelContentTouches = YES;

Moreover, a UIScrollView implements a method touchesShouldCancelInContentView.

The default returned value is YES if view is not a UIControl object; otherwise, it returns NO.

This means that UIScrollView does not attempt to cancel touches in UIButtons which prevents scrolling. Additionally, you can subclass UIScrollView and override touchesShouldCancelInContentView to return YES when content view object is a UIButton.

Upvotes: 2

Related Questions