【问题标题】:UICollectionview and cellsUICollectionview 和单元格
【发布时间】:2023-03-27 21:12:01
【问题描述】:

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

我有一个包含 12 个单元格的 UICollectionView。我将 collectView 设置为仅水平滚动,并且单元格彼此相邻排列。我还打开了分页,因此我可以使用 UIPageControll 来指示滚动处于活动状态。

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

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

【问题讨论】:

  • 缩小集合视图?

标签: ios iphone objective-c uicollectionview


【解决方案1】:

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

这里我使用的是水平滚动方向,您可以在垂直方向以同样的方式执行此操作。 希望这会有所帮助

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

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

【讨论】:

  • 谢谢 - 但是我需要它们动态的是它的网页内容。静态数据的好主意。
  • @Tander 如果你的单元格是动态的,那么你可以使用上面的代码。试试这个
【解决方案2】:

作为 Marc said,您可以简单地控制集合视图的大小。

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

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;

【讨论】:

  • 这很好用。需要稍微调整 - 但它解决了这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多