Scrollview Not Scrolling When Dragging on Buttons

ScrollView not scrolling when dragging on buttons

This is happening because UIButton subviews of the UIScrollView (I assume buttons are added as subviews in your case) are tracking the touches and not the scroll view. UIScrollView method touchesShouldCancelInContentView is the key here. According to its description: "The default returned value is YES if view is not a UIControl object; otherwise, it returns NO.", i.e. for UIControl objects (buttons), UIScrollView does not attempt to cancel touches which prevents scrolling.

So, to allow scrolling with buttons:

  1. Make sure UIScrollView property canCancelContentTouches is set to YES.
  2. Subclass UIScrollView and override touchesShouldCancelInContentView to return YES when content view object is a UIButton, like this:
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
if ( [view isKindOfClass:[UIButton class]] ) {
return YES;
}

return [super touchesShouldCancelInContentView:view];
}

UIButton that will ignore a 'drag' and pass it to UIScrollView

As explained in this answer, a UIButton or other UIControl that is a subview of a scroll view will automatically respond to taps while letting the scroll view handle drags. However, buttons that are subviews of the scroll view will also move with the scrolled content, rather than remaining in the same position on the screen as the content scrolls beneath them. I assume this is why you don't want to put the buttons into the scroll view.

If that's the case, you can get the desired behavior with one more step. Put all your buttons into a UIView that is a subview of the scroll view, then in the scrollViewDidScroll method of the scroll view's delegate, set that view's frame.origin to the scroll view's contentOffset. I just implemented this in my app and it's working great, without having to do any subclassing or get involved with the responder chain or touch events.

UIButtons not working in Scroll View


  • First make the button to custom type
  • Select button from storyboard then on right attributed inspector change its "state config" to whatever you need like Highlighted, selected, Disabled and default and choose the colour for each state.
  • Now you can see the colour change on that button.

Scrollview not scrolling subview in autolayout

Your content view is not embedded in your scroll view.

UIButton Doesn't allow UIScrollView to scroll

As long as you have the Cancellable Content Touches in Interface Builder set it should work. You can also set it in code:

scrollView.canCancelContentTouches = YES;


Related Topics



Leave a reply



Submit