【问题标题】:How do I initialize a UICollectionViewController with items that are sized relative to the container?如何使用相对于容器大小的项目初始化 UICollectionViewController?
【发布时间】:2014-11-17 23:24:48
【问题描述】:

我正在尝试布局视图网格。每行应该有 3 个视图。我试图这样定义我的UICollectionViewController 的构造函数:

- (id)initWithDefaultLayout
{
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    CGFloat dimension = floorf(self.view.frame.size.width / 3.0f);
    layout.itemSize = CGSizeMake(dimension, dimension);
    layout.minimumInteritemSpacing = 1.0f;
    layout.minimumLineSpacing = 1.0f;
    return [super initWithCollectionViewLayout:layout];
}

程序在访问 self.view 的行上崩溃了:

NSException found: UICollectionView 必须用非零初始化 布局参数

我想loadView 的内部实现看到UICollectionViewLayout 没有设置并抛出异常。

我将如何以干净的方式解决此问题?如果我对项目的宽度进行硬编码,代码会很脆弱,因为 iOS 屏幕尺寸不同。此外,在某些情况下,此视图控制器以模态方式呈现(小于屏幕尺寸)。

【问题讨论】:

    标签: ios iphone cocoa-touch uicollectionview


    【解决方案1】:

    为什么不覆盖 UICollectionViewDelegateFlowLayout protocol 的 sizeForItemAtIndexPath 方法 - collectionView:layout:sizeForItemAtIndexPath:

    那么你只需提供如下内容:

    - (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    
        CGFloat viewWidth = CGRectGetWidth(self.view.bounds);
    
        int numCellsInRow = 3;
    
        // adjust for the spacing
        viewWidth -= ((numCellsInRow+1)*1.0f); 
    
        CGFloat dimension = viewWidth/(float)numCellsInRow;
    
    
        return CGSizeMake(dimension, dimension);
    }
    

    【讨论】:

    • 是的。这使得编程类似于UITableView
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2013-03-12
    • 2013-06-27
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多