參考Making two UIScrollViews follow each others scrolling,我通過將UIScrollView委託設置爲父視圖控制器的兩個滾動視圖並調用scrollViewDidScroll方法來完成此操作。
- (void)matchScrollView:(UIScrollView *)first toScrollView:(UIScrollView *)second {
CGPoint offset = first.contentOffset;
offset.x = (second.contentOffset.x/second.frame.size.width) * first.frame.size.width;
first.contentOffset = offset;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
if([scrollView isEqual:firstScrollView]) {
isSecondScrolling = NO;
} else if ([scrollView isEqual:secondScrollView]) {
isSecondScrolling = YES;
}
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if ([scrollView isEqual:firstScrollView] && isSecondScrolling == NO) {
[self matchScrollView:secondScrollView toScrollView:firstScrollView];
} else if ([scrollView isEqual:_midPanelScrollView] && isSecondScrolling == YES) {
[self matchScrollView:firstScrollView toScrollView:secondScrollView];
}
}
但是我加了布爾isSecondScrolling,從開始時secondScrollView正在滾動matchScrollView停止firstScrollView。否則,會導致每次滾動後secondScrollView的框架略微關閉。