是否可以将UICollectionView中的滚动限制为集合中项目的子集?

时间:2014-07-09 17:27:15

标签: ios uiscrollview uicollectionview

是否可以将UICollectionView中的滚动限制为集合中项目的子集?

我有一个UICollectionView,一次显示一个项目。每个项目占据屏幕的整个宽度。用户可以在项目之间水平滚动。

有时我希望能够限制用户根据特定条件在项目子集之间滚动。

例如,视图可能包含项目1到20,但我只希望用户能够在项目7和9之间滚动。

我尝试将contentSize更改为显示所需项目所需的宽度,然后更改contentOffset,但这不起作用。

2 个答案:

答案 0 :(得分:5)

我昨天花了6个小时研究这个问题,但在发布问题的几分钟内,我找到了解决方案的关键:

Cancel current UIScrollView touch

该答案描述了如何取消滚动。很简单的是,当用户试图滚动超出为他们设置的限制时,用户看不到任何滚动行为;没有闪烁,没有。

我想出的解决方案是确定我希望用户看到的项目的起始和结束偏移,然后如果新偏移在开始之前或结束之后偏移,则取消在scrollViewDidScroll中滚动:< / p>

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    //Prevent user from scrolling to items outside the desired range
    if (scrollView.contentOffset.x < self.startingOffset ||
        scrollView.contentOffset.x > self.endingOffset) {
        scrollView.panGestureRecognizer.enabled = NO;
        scrollView.panGestureRecognizer.enabled = YES;
    }
}

答案 1 :(得分:2)

Swift版本:

  override func scrollViewDidScroll(scrollView: UIScrollView) {
    //Prevent user from scrolling to items outside the desired range
    if (scrollView.contentOffset.x < self.startingOffset ||
      scrollView.contentOffset.x > self.endingOffset) {
        scrollView.panGestureRecognizer.enabled = false
        scrollView.panGestureRecognizer.enabled = true
    }
  }
相关问题