首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >UICollectionView不会在设置contentInset后滚动

UICollectionView不会在设置contentInset后滚动
EN

Stack Overflow用户
提问于 2017-08-09 02:12:28
回答 1查看 1.2K关注 0票数 3

我有一个集合视图,它水平滚动并跨越其父视图的全部宽度。实现分页的廉价方法是将单元格宽度设置为集合视图宽度的1/3,并设置与左和右内容内嵌相同的宽度。

我在IB中禁用滚动,用左、右滑动识别器替换。我的代码几乎不需要设置contentInset就能工作,但是设置contentInset似乎可以防止滚动发生。

代码语言:javascript
代码运行次数:0
运行
复制
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    CGFloat itemWidth = self.collectionView.bounds.size.width/3.0;
    NSInteger count = [self collectionView:self.collectionView numberOfItemsInSection:0];
    self.collectionView.contentSize = (CGSize){ .width=itemWidth*count, .height=self.collectionView.bounds.size.height };
    // uncomment this line, and the scroll code in the swipes below fails to work
    //self.collectionView.contentInset = UIEdgeInsetsMake(0, itemWidth, 0, itemWidth);
    self.collectionView.contentOffset = (CGPoint){ .x=self.collectionView.contentSize.width/2.0, .y=0 };
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = self.view.bounds.size.width/3.0;
    return (CGSize){ .width=width, .height=collectionView.bounds.size.height };
}

这段代码处理刷卡..。

代码语言:javascript
代码运行次数:0
运行
复制
- (NSIndexPath *)centerIndexPath {
    CGRect visibleRect = (CGRect){.origin = self.collectionView.contentOffset, .size = self.collectionView.bounds.size};
    CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
    return [self.collectionView indexPathForItemAtPoint:visiblePoint];
}

- (void)swipeLeft:(UISwipeGestureRecognizer *)gr {
    NSIndexPath *centerIndexPath = [self centerIndexPath];
    NSLog(@"at %@", centerIndexPath);

    if (centerIndexPath.row < [self collectionView:self.collectionView numberOfItemsInSection:0]-1) {
        [self.collectionView scrollToItemAtIndexPath:centerIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }
}

- (void)swipeRight:(UISwipeGestureRecognizer *)gr {
    NSIndexPath *centerIndexPath = [self centerIndexPath];
    NSLog(@"at %@", centerIndexPath);

    if (centerIndexPath.row > 0) {
        [self.collectionView scrollToItemAtIndexPath:centerIndexPath atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
    }
}

所有这些都能工作,除非我在上面的设置中设置了contentInsets。然后,即使我到达调试器中的scrollToItemAtIndexPath:代码,也不会发生滚动。

拥有这些内嵌是很重要的,因为我希望用户理解中心项是所选的项。

有人能解释一下为什么contentInset会滚动,以及如何修复吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-09 05:29:54

看起来UICollectionView有自己的内置方式来处理嵌入式:

ref/doc/uid/TP40012334-CH3-SW1

使用区段插入来调整内容区段嵌入的边距是调整单元格可用空间的一种方法。您可以使用内嵌在节的页眉视图之后和页脚视图之前插入空间。您还可以使用内嵌在内容的两侧插入空间。图3-5演示了嵌入如何影响垂直滚动流布局中的某些内容.

图3-5节嵌入更改了布局单元的可用空间

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45580623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档