UICollectionView中不同的单元大小

在我的iphone应用程序中,我正在集合视图上显示图像。 我从url获取图片,并通过url获取图片大小。 例如: – 假设有两种图像风景和肖像。我得到的价值P为肖像图像和L为风景图像

如何自定义collectionView单元格的大小?

使用这个UICollectionViewDelegateFlowLayout方法

  - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; 

1)你可以维护和交换多个布局对象,但有一个更简单的方法。 只需将以下内容添加到您的UICollectionViewController子类并根据需要resize:

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { // Adjust cell size for orientation if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) { return CGSizeMake(170.f, 170.f); } return CGSizeMake(192.f, 192.f); } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [self.collectionView performBatchUpdates:nil completion:nil]; } 

调用-performBatchUpdates:completion:将使布局无效,并使用animation调整单元格的大小(如果没有额外的调整,只需将nil传递给两个块参数)。

2)不要在-collectionView:layout:sizeForItemAtIndexPath对项目大小进行硬编码,只需将collectionView的边界的高度或宽度除以要放在屏幕上的单元格的数量即可。 如果您的UICollectionView水平滚动,请使用高度;如果UICollectionView滚动,请使用宽度。

这就是我所做的。 我首先根据屏幕的大小设置单元格的大小(以便我们可以在每一行中获得最佳的图像数量)。 您可能需要更改数字以适应您的原因。

 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ CGFloat widthOfCell =(self.view.frame.size.width-30)/2; CGFloat heightOfCell =widthOfCell * 1.33; CGSize returnValue = CGSizeMake(widthOfCell, heightOfCell); returnValue.height += 5; returnValue.width += 5; return returnValue; } 

然后,我使用image processing方法来确定风景或肖像状态,(对于我的应用程序),我决定让每张图像都是一幅肖像:

  if (sourceImage.size.width>sourceImage.size.height) { sourceImage = [[UIImage alloc] initWithCGImage: sourceImage.CGImage scale: 1.0 orientation: UIImageOrientationRight]; } 

如果你想反过来,用&交换>

CAVEAT:我的旋转方法不考虑如果图片左右指向。 换句话说,如果图像是颠倒的风景,我的代码无法识别。 我希望别人能帮助你,但我希望我没有偏离轨道! 🙂

如果你需要在单元格上显示dynamic图像,把你的视图控制器中的图像名称保存到你的控制器中,并使用下面的代码,

 let imageData = ["image1","image2","image3","image4"] extension yourViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let photo = UIImage(named: imageData[indexPath.row]) return CGSize(width: (photo?.size.width)!, height: (photo?.size.height)!) } 

}