繁体   English   中英

UICollectionview和单元格

[英]UICollectionview and cells

我是第一次使用集合视图,我不知道该怎么做......

我有一个带12个单元格的UICollectionView。 我将collectView设置为仅水平滚动,并且单元格彼此相邻排列。 我也打开了分页,所以我可以使用UIPageControll来指示滚动是否有效。

我希望集合视图在任何时候只在屏幕上显示四个单元格。 当视图加载时,我得到四个单元格,没问题。 但是当我水平滚动时,我得到了4个半小区。 从来没有四个。

有没有办法告诉集合视图一次只显示四个单元格?

在此输入图像描述

在此输入图像描述

如果不需要动态,您可以在集合视图中静态添加单元格(项目)的数量。

在这里我使用Scroll Direction Horizo​​ntal你可以在垂直方向上做同样的方式。 希望这会有所帮助

你也可以这样做。 只需将此代码复制到视图控制器中并进行一些更改即可。

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

   NSIndexPath *indexPath;
    for (UICollectionViewCell *cell in [self.collectionView visibleCells]) {
        indexPath = [self.collectionView indexPathForCell:cell];
        NSLog(@"%@",indexPath);
    }

    UICollectionViewCell *cell =(UICollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];

    //finally get the rect for the cell
    CGRect cellRect = cell.frame;


    self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, cellRect.origin.y);
}

正如Marc 所说 ,您可以简单地控制集合视图的大小。

如果更改大小不实用,则可以在集合视图上设置内容插入。

CGFloat cellWidth = … // Cell width
CGFloat collectionViewWidth = … // Collection View Width
CGFloat desiredCollectionViewWidth = cellWidth * 4.0;

CGFloat horizontalInset = collectionViewWidth - desiredCollectionViewWidth;

// To center the collection view
UIEdgeInsets inset = UIEdgeInsetsMake(0, horizontalInset/2, 0, horizontalInset/2);
self.collectionView.contentInset = inset;

// Or, to left justify the collection view
UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, 0, horizontalInset);
self.collectionView.contentInset = inset;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM