【问题标题】:Is it possible to restrict scrolling within a UICollectionView to a subset of the items in the collection?是否可以将 UICollectionView 内的滚动限制为集合中项目的子集?
【发布时间】:2014-07-09 17:27:14
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您应该在- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 中返回正确的值并跟踪您想要以某种方式显示的模型对象

标签: ios uiscrollview uicollectionview


【解决方案1】:

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

Cancel current UIScrollView touch

该答案描述了如何取消滚动。巧妙的是,当用户尝试滚动超出为他们设置的限制时,他们看不到任何滚动行为。没有闪烁,什么都没有。

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

- (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;
    }
}

【讨论】:

    【解决方案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
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-01
      • 2022-01-04
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      相关资源
      最近更新 更多