如何获取ios中某个部分的行数

Nik*_*iks 7 objective-c ios uicollectionview

我正在处理集合视图,我想要在上一节中的行数.是否有任何方法在部分返回行数.请帮我.

Wil*_*rge 5

UICollectionView dataSource您需要实现以显示单元格的委托方法可以手动调用。

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
Run Code Online (Sandbox Code Playgroud)

因此您可以使用以下方式调用它:

NSInteger numberOfRows = [self collectionView:self.collectionView numberOfItemsInSection:MAX(0, currentSection - 1)];
Run Code Online (Sandbox Code Playgroud)

您不希望出现越界异常,因此我将其上限设置为 0*

编辑

@holex 提出了一个非常好的观点 - 我假设你只有一栏。

如果您知道物品宽度的大小,您可以执行以下操作:

//Assuming a fixed width cell

NSInteger section = 0;
NSInteger totalItemsInSection = [self.feedCollectionView numberOfItemsInSection:section];

UIEdgeInsets collectionViewInset = self.feedCollectionView.collectionViewLayout.sectionInset;
CGFloat collectionViewWidth = CGRectGetWidth(self.feedCollectionView.frame) - collectionViewInset.left - collectionViewInset.right;
CGFloat cellWidth = [self.feedCollectionView.collectionViewLayout itemSize].width;
CGFloat cellSpacing = [self.feedCollectionView.collectionViewLayout minimumInteritemSpacing];

NSInteger totalItemsInRow = floor((CGFloat)collectionViewWidth / (cellWidth + cellSpacing));
NSInteger numberOfRows = ceil((CGFloat)totalItemsInSection / totalItemsInRow);

NSLog(@"%@", @(numberOfRows));
Run Code Online (Sandbox Code Playgroud)

我们确定一行中将出现多少个项目,以便能够确定该部分中的行数。