iOS: How sync two UIScrollview

为君一笑 提交于 2019-12-05 15:08:38

You can use topScrollView.panGestureRecognizer and bottomScrollView.panGestureRecognizer to take both gesture recognizers and add them to a common superview enclosing both scroll views. Pan gestures on this superview would then be recognized by both children.

You'll most likely also need to be the delegate of both recognizers and let them be recognized simulaneously:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

I worked out the solution according to jszumski's answer. However, my situation is two vertical UIScrollViews side by side (scrollViewLeft and scrollViewRight). It should work for horizontal UIScrollViews without too much modification.

First, create a custom UIScrollView.

//.h file

@interface CSScrollView : UIScrollView

@end

//.m file

@implementation CSScrollView


-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{

    return YES;

}

@end

Secondly, in your mainview,

- (void)viewDidLoad {

    [super viewDidLoad];


    [self.view addGestureRecognizer:self.scrollViewLeft.panGestureRecognizer];

    [self.view addGestureRecognizer:self.scrollViewRight.panGestureRecognizer];

}

That's everything I need to set up two synchronized scrollviews. The real effect is much better than the regular way of sending/subscribing notifications in scrollview's scrollViewDidScroll and synchronize the contentOffset.

@jszumski answer in Swift

  1. Create a custom subclass of UIScrollView
  2. Conform to UIGestureRecognizer delegate
  3. Override the gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:) GestureRecognizerDelegate method
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
  1. Both collection views need to have the same superview. Add both gesture recognizers to your superview
yourSuperview.addGestureRecognizer(scrollView1.panGestureRecognizer)
yourSuperview.addGestureRecognizer(scrollView1)

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!