【问题标题】:How to make UICollectionViewFlowLayout itemSize dynamic for screen size如何使 UICollectionViewFlowLayout itemSize 根据屏幕尺寸动态变化
【发布时间】:2014-11-13 04:20:59
【问题描述】:

我正在以编程方式工作(没有情节提要),并且无法为不同的屏幕尺寸制作动态 layout.itemSize。我收到此错误消息:

“UICollectionView 必须使用非零布局参数初始化”

在我的实现文件中使用以下代码:

- (instancetype)init 
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    CGSize size = self.collectionView.bounds.size;

    layout.itemSize = CGSizeMake(size.width, size.height);

    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];

    layout.minimumLineSpacing = 100.0;

    layout.headerReferenceSize = CGSizeMake(0.0, 50.0);

    return (self = [super initWithCollectionViewLayout:layout]);
}

如果我对 layout.itemSize 使用“100,100”,则不会收到错误消息。有没有办法让它动态化?

我是 Objective-C 的新手,所以如果我做错了什么,我将不胜感激。

【问题讨论】:

    标签: ios objective-c uicollectionview


    【解决方案1】:

    需要使用流委托方法:

    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        CGSize cellSize = CGSizeMake(width, height);
    
        return cellSize;
    }
    

    您可以根据需要指定宽度和高度浮点值。

    例如,假设您的 CollectionView 是垂直的,并且您想要一个短的标题视图、一个大的中间视图和一个小的页脚视图,那么您可以执行以下操作:

    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        CGSize cellSize;
    
        cellSize.width = self.view.bounds.size.width;
    
        if(indexPath.row == 0)
        {
            // header view height
            cellSize.height = 100;
        }
        else if(indexPath.row == 1)
        {
            // body view height
            cellSize.height = 500;
        }
        else
        {
            // assuming number of items is 3, then footer view is last view
            // footer view height
            cellSize.height = 100;
        }
    
        return cellSize;
    }
    

    【讨论】:

      【解决方案2】:

      将以下委托方法添加到您的集合视图

      -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
       {
      UIImage *image;
      long row = [indexPath row];
      
      image = [UIImage imageNamed:_carImages[row]];
      
      return image.size;
       }
      

      这里有一个链接可以帮助你enter link description here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 2013-07-17
        • 2018-05-09
        • 1970-01-01
        • 2011-06-15
        相关资源
        最近更新 更多