我有两个带垂直滚动的UIScrollView:foreground
和background
。用户只能与前者互动;后者以编程方式移动。我怎样才能使用户滚动foreground
时,background
按比例的速率滚动?例如,对于foreground
滚动的每4px,background
将向同一方向滚动1px。
如何在Swift2中实现这种关系?
答案 0 :(得分:2)
将您的self设置为scrollView委托 -
self.foregroundScrollView.delegate = self
并使用UIScrollViewDelegate方法:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
self.lastY = scrollView.contentOffset.y;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// Calculate how much distance the scrollView has travelled since last scroll
CGFloat currentY = scrollView.contentOffset.y;
CGFloat difference = currentY - self.lastY;
// Set new contentOffset for your background scrollView
CGPoint currentBackgroundOffset = self.backgroundScrollView.contentOffset;
currentBackgroundOffset.y += difference/4;
self.backgroundScrollView.contentOffset = currentBackgroundOffset;
// Don't forget to update the lastY
self.lastY = currentY;
}
夫特:
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
lastY = scrollView.contentOffset.y
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// Calculate how much distance the scrollView has travelled since last scroll
let currentY = scrollView.contentOffset.y
let difference = currentY - lastY
// Set new contentOffset for your background scrollView
var currentBackgroundOffset = backgroundScrollView.contentOffset
currentBackgroundOffset.y += difference/4
backgroundScrollView.contentOffset = currentBackgroundOffset
// Don't forget to update the lastY
lastY = currentY
}