如何将两个UIScrollView实例缩放到相同级别?

时间:2011-04-03 23:59:38

标签: iphone objective-c uiscrollview

我有两个UIScrollView实例,我想让它们同时缩放。

任何人都有这方面的经验吗?

我正在使用NSNotificationCenter告诉我的对象何时缩放。最初我以为我可以以某种方式进入当前可见的矩形,只需拨打zoomToRect:,但我没有办法做到这一点。我现在拥有的是设置zoomScalecontentOffset属性。它看起来像这样:

- (void)registerForZoomNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(receiveZoomNotification:) 
                                             name:ZOOM_NOTIFICATION_IDENTIFIER 
                                           object:nil];
}

- (void)receiveZoomNotification:(NSNotification*)notification {

UIScrollView *currentScrollView = (UIScrollView*)[notification object];

// zoomLevel
[(UIScrollView*)self.view setZoomScale:currentScrollView.zoomScale animated:NO];

// contentOffset
[(UIScrollView*)self.view setContentOffset:currentScrollView.contentOffset animated:NO];
}

#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidZoom:(UIScrollView *)pageScrollView {

[[NSNotificationCenter defaultCenter] postNotificationName:ZOOM_NOTIFICATION_IDENTIFIER object:pageScrollView];

}

虽然它不起作用,但看起来非常不稳定。想法有人吗?我应该采取不同的方法吗?

编辑:我应该澄清两个滚动视图同时不可见。它们在完全相同的时间滚动并不重要,只有滚动视图与滚动完成后的另一个滚动视图处于相同的缩放级别(和可见的矩形)。

2 个答案:

答案 0 :(得分:7)

更简单的方法是为您的UIView控件实现UIScrollViewDelegate协议,该协议管理2 UIScrollView2

你的.h文件中的

只需添加@interface声明

@interface yourUIViewControll : UIViewControll <UIScrollViewDelegate> {
    UIScrollView *aUIScrollView;
    UIScrollView *bUIScrollView;
}

现在,当用户滚动或缩放其中一个UIScrollView时,您可以使用所需的所有方法 所以,例如,你想知道一个人在缩放或滚动时想要让另一个人进行缩放和滚动,你需要特别注意这两个

in .m:

// called when a UIScrollView is zooming:
    - (void)scrollViewDidZoom:(UIScrollView *)zoomViewInUse{
    // just to test in log window:
    // NSLog(@"changing zoom...  scrollViewInUse.zoomScale: %.5f", zoomViewInUse.zoomScale);
    //force both UIScrollViews to zoom at the new value
        aUIScrollView.zoomScale = zoomViewInUse.zoomScale;
        bUIScrollView.zoomScale = zoomViewInUse.zoomScale;
    }


// called when a UIScrollView is scrolling:
    - (void)scrollViewDidScroll:(UIScrollView *)scrollViewInUse{
       // just to test in log window:
       //  NSLog(@"scrollViewInUse..contentOffset.x:%.1f", scrollViewInUse.contentOffset.y);
       //force both UIScrollViews to scroll at the new value
        aUIScrollView.contentOffset = scrollViewInUse.contentOffset;
        bUIScrollView.contentOffset = scrollViewInUse.contentOffset;
    }

答案 1 :(得分:0)

我目睹的不稳定行为是因为我在滚动时没有发送通知,只是放大了。当我添加以下附加委托方法时,一切正常:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
     [[NSNotificationCenter defaultCenter] postNotificationName:ZOOM_NOTIFICATION_IDENTIFIER object:scrollView];
}