ScrollView not scrolling when dragging on buttons

2019-01-08 06:53发布

I have a scroll view that used to scroll when it didn't have buttons all over it. Now it does, and when dragging the mouse (on simulator) nothing happens (i think because the buttons are being pushed). How can I make this right?

5条回答
贼婆χ
2楼-- · 2019-01-08 07:07

One thing to try if you're seeing this in a simulator is to run on an actual phone. I couldn't scroll in the simulator but no prob on my phone.

查看更多
\"骚年 ilove
3楼-- · 2019-01-08 07:08

I founded this question looking for the swift solution for this problem, I "translated" it like this:

class UIButtonScrollView: UIScrollView {

    override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
        if (view.isKindOfClass(UIButton)) {
            return true
        }

        return super.touchesShouldCancelInContentView(view)

    }

}

hope this could help

查看更多
4楼-- · 2019-01-08 07:18

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];
}
查看更多
等我变得足够好
5楼-- · 2019-01-08 07:19

In my case, I solved it with this way.

in ViewDidLoad

self.scrollView.panGestureRecognizer.delaysTouchesBegan = self.scrollView.delaysContentTouches;

in .m

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
    if ([view isKindOfClass:[UIControl class]]) return YES;
    return NO;
}
查看更多
6楼-- · 2019-01-08 07:33

Swift 3 Solution

override func touchesShouldCancel(in view: UIView) -> Bool {
    if view is UIButton {
        return true
    }
    return super.touchesShouldCancel(in: view)
}
查看更多
登录 后发表回答