繁体   English   中英

UICollectionview中的不同单元格大小

[英]Different cell size in UICollectionview

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

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

使用此UICollectionViewDelegateFlowLayout方法

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

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水平滚动,则使用高度;如果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;

}

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

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

如果您想反过来,请将< ><交换

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

如果您需要在单元格上显示动态图像,并将图像名称保存到视图控制器中,请使用以下内容将swlay扩展到viewcontroller;

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

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM