iOS:如何同步两个 UIScrollview [英] iOS: How sync two UIScrollview
问题描述
我有两个水平的 UIScrollview
.当用户在其中任何一个中拖动手指时,我想同步它们的滚动.这是我的代码:
I have two horizontal UIScrollview
s. I want to synchronise their scrolling when user drag fingers in either of them. Here is my code:
self.topScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
self.topScrollView.delegate = self;
self.topScrollView.bounces = YES;
self.bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
self.bottomScrollView.delegate = self;
self.bottomScrollView.bounces = YES;
...
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
if (scrollView == self.topScrollView)
{
self.bottomScrollView.delegate = nil;
}
else
{
self.topScrollView.delegate = nil;
}
...
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
...
self.topScrollView.delegate = self;
self.bottomScrollView.delegate = self;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
...
self.topScrollView.delegate = self;
self.bottomScrollView.delegate = self;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// Sync the two scroll views
if (scrollView == self.topScrollView)
{
[self.bottomScrollView setContentOffset:scrollView.contentOffset animated:NO];
}
else
{
[self.topScrollView setContentOffset:scrollView.contentOffset animated:NO];
}
...
}
两个滚动视图确实同步滚动,但是,问题是所有的弹跳和减速都消失了.整个滚动运动变得非常僵硬.如果我删除所有同步代码,那么每个滚动视图都可以单独正常工作.那么,问题是什么?还是UIScrollView
不能同步?
The two scroll views do scroll synchronously, however, the problem is all the bouncing and deceleration are gone. The whole scrolling movement becomes really rigid. If I remove all the syncing code, then each scroll view works just fine individually.
So, what is the problem? Or can UIScrollView
not be synchronised?
推荐答案
您可以使用 topScrollView.panGestureRecognizer
和 bottomScrollView.panGestureRecognizer
来获取两个手势识别器并将它们添加到包含两个滚动视图的公共超级视图.然后,两个孩子都可以识别此超级视图上的平移手势.
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;
}
这篇关于iOS:如何同步两个 UIScrollview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!