只是为了好玩,另一种方法是只保留分页和水平滚动集,添加一个方法来更改数组项的顺序以从“从上到下,从左到右”转换为视觉上的“从左到右,从上到底部'并用空的隐藏单元格填充中间单元格以使间距正确。如果 9 个网格中有 7 个项目,则如下所示:
[1][4][7]
[2][5][ ]
[3][6][ ]
应该成为
[1][2][3]
[4][5][6]
[7][ ][ ]
所以 1=1、2=4、3=7 等等,6=空。您可以通过计算总行数和总列数对它们重新排序,然后计算每个单元格的行数和列数,更改列的行数,反之亦然,然后您就有了新的索引。当单元格没有与图像对应的值时,您可以返回一个空单元格并设置cell.hidden = YES;
为它。
它在我构建的音板应用程序中运行良好,所以如果有人想要工作代码,我会添加它。只需要很少的代码就可以使这个技巧起作用,听起来比它更难!
更新
我怀疑这是最好的解决方案,但根据要求,这里的工作代码:
- (void)viewDidLoad {
// Fill an `NSArray` with items in normal order
items = [NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"Some label 1", @"label", @"Some value 1", @"value", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Some label 2", @"label", @"Some value 2", @"value", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Some label 3", @"label", @"Some value 3", @"value", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Some label 4", @"label", @"Some value 4", @"value", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Some label 5", @"label", @"Some value 5", @"value", nil],
nil
];
// Calculate number of rows and columns based on width and height of the `UICollectionView` and individual cells (you might have to add margins to the equation based on your setup!)
CGFloat w = myCollectionView.frame.size.width;
CGFloat h = myCollectionView.frame.size.height;
rows = floor(h / cellHeight);
columns = floor(w / cellWidth);
}
// Calculate number of sections
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return ceil((float)items.count / (float)(rows * columns));
}
// Every section has to have every cell filled, as we need to add empty cells as well to correct the spacing
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return rows*columns;
}
// And now the most important one
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier@"myIdentifier" forIndexPath:indexPath];
// Convert rows and columns
int row = indexPath.row % rows;
int col = floor(indexPath.row / rows);
// Calculate the new index in the `NSArray`
int newIndex = ((int)indexPath.section * rows * columns) + col + row * columns;
// If the newIndex is within the range of the items array we show the cell, if not we hide it
if(newIndex < items.count) {
NSDictionary *item = [items objectAtIndex:newIndex];
cell.label.text = [item objectForKey:@"label"];
cell.hidden = NO;
} else {
cell.hidden = YES;
}
return cell;
}
如果您想使用该didSelectItemAtIndexPath
方法,您必须使用与cellForItemAtIndexPath
获取相应项目相同的转换。如果您有单元格边距,则需要将它们添加到行和列计算中,因为这些必须正确才能使其起作用。