指定UICollectionView的行号和列号

我想要显示一个UICollectionView,其中每行包含2行和100个单元格。

// 1 - (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section { return 100; } // 2 - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView { return 2; } // 3 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { MyCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; cell.lbl.text = @"Data"; return cell; } 

我得到这个:

在这里输入图像说明

我怎样才能为UICollectionView指定行号? 我想创build一个2×100表。

尝试这个:

 // 1 - (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section { return 2; } // 2 - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView { return 100; } // 3 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { MyCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; cell.lbl.text = @"Data"; return cell; } 

对于每行3个单元格..添加此代码。

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { return CGSizeMake(collectionView.frame.size.width/3.2 , 100); } 

Swift每行3行 (使用@SakhshiSingla答案)

 override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.frame.size.width/3.2, height: 100) } 

在任何方向兼容的收集视图中实现n列的更一般方法是

  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { // flow layout have all the important info like spacing, inset of collection view cell, fetch it to find out the attributes specified in xib file guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return CGSize() } // subtract section left/ right insets mentioned in xib view let widthAvailbleForAllItems = (collectionView.frame.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right) // Suppose we have to create nColunmns // widthForOneItem achieved by sunbtracting item spacing if any let widthForOneItem = widthAvailbleForAllItems / nColumns - flowLayout.minimumInteritemSpacing // here height is mentioned in xib file or storyboard return CGSize(width: CGFloat(widthForOneItem), height: (flowLayout.itemSize.height)) } 

假设单元格的大小允许,分段的数量决定了每行中有多less个单元格。

一节将始终开始一个新的行。