UICollectionview中的不同单元格大小

时间:2013-04-17 13:46:07

标签: iphone ios uicollectionview uicollectionviewcell

在我的iphone应用程序中,我在集合视图中显示图像。 我从网址获取图片,网址也是我获得的图片大小。 例如: - 假设有两种图像横向和纵向。我得到肖像图像的值P和景观图像的L

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

4 个答案:

答案 0 :(得分:64)

使用此UICollectionViewDelegateFlowLayout方法

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

答案 1 :(得分:9)

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

- (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:将使布局无效并使用动画调整单元格的大小(如果您没有进行额外的调整,则可以将nil传递给两个块参数)。

2)不要在-collectionView:layout:sizeForItemAtIndexPath中对项目大小进行硬编码,只需将collectionView的边界的高度或宽度除以您想要适合屏幕的单元格数。如果UICollectionView水平滚动,则使用高度;如果垂直滚动,则使用宽度。

答案 2 :(得分:2)

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

-(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;

}

然后我使用图像处理方法来确定横向或纵向状态,并且(对于我的应用程序)我决定让每张图像都成为肖像:

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

如果您希望反过来,请将>换成<

CAVEAT:如果图片指向左或右,我的旋转方法不会考虑。换句话说,如果图像是颠倒的横向,我的代码无法识别。我希望其他人可以帮助你,我希望我没有偏离轨道! :)

答案 3 :(得分:1)

对于swift将flowlayout扩展到viewcontroller,如果你需要在cell make变量上显示动态图像,它将图像名称保存到你的视图控制器中并使用它:

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)!)

}

}

相关问题