故事板编辑器中单元格的大小只是为了帮助您设计单元格。由于每个原型单元格可以具有不同的大小,因此 UICollectionView 不知道为所有单元格选择哪个单元格的大小。这就是为什么您要单独设置单元格的实际大小。您可以在设计器中通过选择集合视图并在“集合视图大小”标题下的大小检查器中设置其单元格大小宽度和高度来完成此操作。
或者,您可以重写以下方法并返回一个 CGSize 对象,该对象指定要用于每个单元格的大小。使用这种方法,您实际上可以让每个单元格具有不同的大小:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
例子:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(100, 100);
}
您的视图控制器需要成为 UICollectionViewDelegateFlowLayout 的委托才能调用此方法。因此,不要忘记将该委托声明添加到视图控制器的 .h 文件中,例如:
@interface MyViewController () <UICollectionViewDelegateFlowLayout>
Swift
extension MyViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}