两个UIScrollViews,同步滚动

时间:2012-04-26 08:51:33

标签: iphone ios cocoa-touch uiscrollview uikit

我有两个UIScrollViews,它们彼此重叠。

                                        UIView
                                           |
                              --------------------------
                              |                        |
                         UIScrollView1            UIScrollView2

我希望以下列方式工作。如果我滚动UIScrollView2,UIScrollView1也应滚动相同的contentOffset。它必须同步完成,因此使用scrollViewDidScroll不是一种选择。你们有什么想法,怎么办?

源代码

    _prContentGridView = [[PRContentGridView alloc] initWithFrame:frame];
    _prContentGridView.minimumZoomScale = 0.25;
    _prContentGridView.maximumZoomScale = 2.0;
    _prContentGridView.delegate = self;

    _prBackgroundGridView = [[PRBackgroundGridView alloc] initWithFrame:frame];

    [self addSubview:_prBackgroundGridView];
    [self addSubview:_prContentGridView];

委托方法

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_prContentGridView.scrollEnabled == YES) {
        CGPoint p = CGPointMake(scrollView.contentOffset.x -   _prevousContentOffsetOfContentScrollView.x, scrollView.contentOffset.y - _prevousContentOffsetOfContentScrollView.y);
        [_prBackgroundGridView setContentOffset:p animated:YES];
    }
}

2 个答案:

答案 0 :(得分:8)

使用UIScrollViewDelegate协议方法:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
  if (scrollView == UIScrollView1){
    UIScrollView2.contentOffset = scrollView.contentOffset;
  }else{
    UIScrollView1.contentOffset = scrollView.contentOffset;
  }
}

答案 1 :(得分:2)

你应该试试这个代码, 首先在.h文件中声明IBOutlet,

IBOutlet UIScrollView *FirstScrollView;
IBOutlet UIScrollView *SecondScrollView;

然后尝试这段代码,

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
  if ([scrollView isEqual: FirstScrollView])
  {
            SecondScrollView.contentOffset =
              CGPointMake(FirstScrollView.contentOffset.x, 0);
  }
  else
  {
            FirstScrollView.contentOffset = 
              CGPointMake(SecondScrollView.contentOffset.x, 0);
  }
}