我正在实现一个将滚动方向设置为水平的 uicollection 视图。我还在情节提要中启用了分页选项。在我看来,我可以一次显示 4 个项目。如果我有 5 个项目,第一页有 4 个项目,但第二页有 3 个项目。以前的项目也会显示在第二页上。
我只想问我怎样才能防止这种情况?我希望第一页上有 4 个项目,第二页上只有 1 个项目。我正在考虑添加项目并将它们设置为隐藏以执行此操作。这是解决这个问题的正确方法吗?
谢谢!
也许您可以将 UICollectionView 的 contentSize
属性设置为其bounds
的下一个倍数?
例如,对于单截面集合视图:
NSUInteger itemsPerPage = 4;
NSUInteger pageCount = (NSUInteger) ceilf((float)[collectionView.dataSource numberOfItemsInSection:0] / itemsPerPage);
CGFloat contentWidth = collectionView.bounds.size.width * pageCount;
collectionView.contentSize = CGSizeMake(contentWidth, collectionView.contentSize.height);
我遇到了类似的问题,我以一种相当黑客的方式解决了它,但它有效,我现在很满意。
基本上,我决定做的是用空的UICollectionViewCells填充集合视图页面。
我首先计算一下总共会有多少项目。如果我的 NSFetchedResultsController 提供的项目总数不是 3 的精确倍数,那么我将必要的项目数相加,使总数是 3 的倍数。
例如,如果我返回四个类别,则需要再添加两个类别,使其总共六个:
#define ITEMS_PER_PAGE 3
//...
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
NSArray *sections = [categoriesFetchedResultsController sections];
id <NSFetchedResultsSectionInfo> sectionInfo = sections[section];
NSInteger categoryCount = [sectionInfo numberOfObjects];
NSInteger extraItemsNeeded = ITEMS_PER_PAGE - (categoryCount % ITEMS_PER_PAGE);
NSInteger totalItems = categoryCount + extraItemsNeeded;
NSInteger pages = (NSInteger)(totalItems / ITEMS_PER_PAGE);
self.pageControl.numberOfPages = pages;
return totalItems;
}
然后,当需要生成单元格时,我执行以下操作:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CategoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CategoryCell" forIndexPath:indexPath];
// use a generic UICollectionCell for the "empty cell" case.
UICollectionViewCell *emptyCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EmptyCell" forIndexPath:indexPath];
if (indexPath.row < [[categoriesFetchedResultsController fetchedObjects] count] ) {
NSManagedObject *object = [categoriesFetchedResultsController objectAtIndexPath:indexPath];
NSData *imageData = [object valueForKey:@"thumbnail_data"];
NSString *name = [object valueForKey:@"category_name"];
cell.image.image = [UIImage imageWithData:imageData];
cell.label.text = name;
return cell;
}
return emptyCell;
}
我希望这对将来的某人有所帮助,因为解决这个问题并不像它应该的那样简单,而且我很惊讶流布局不只是自动适当地计算页面。