将一个UIScrollView按比例滚动到另一个

时间:2015-12-05 17:37:43

标签: ios uiscrollview swift2 xcode7

我有两个带垂直滚动的UIScrollView:foregroundbackground。用户只能与前者互动;后者以编程方式移动。我怎样才能使用户滚动foreground时,background按比例的速率滚动?例如,对于foreground滚动的每4px,background将向同一方向滚动1px。

如何在Swift2中实现这种关系?

1 个答案:

答案 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
}