ios - UICollectionView 使用不同高度的单元格

标签 ios objective-c uicollectionview

所以我有一个包含 3 个单元格的 Collection View Controller ,因为每个单元格都有不同的布局。我的图片显示了这一点:

enter image description here

它们都有不同的单元格标识符,因此在我的 cellForItemAtIndexPath 函数中我可以创建特定的单元格,例如:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell;


    if(indexPath.row == 0)
    {
        static NSString *identifier = @"Cell1";
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier     forIndexPath:indexPath];
        [cell setNeedsLayout];
    }
    else if(indexPath.row == 1)
    {
        static NSString *identifier = @"Cell2";
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        [cell setNeedsLayout];
    }
    else
    {
        static NSString *identifier = @"Cell3";
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        [cell setNeedsLayout];
    }

    return cell;
}

但是当我模拟它时,所有单元格的大小都相同:

enter image description here

有没有办法强制单元格为我定义的大小,或者有更合适的方法吗?

最佳答案

试试这个:Custom layout for different cell sizes in UICollectionView

或者使用这个方法:

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

关于ios - UICollectionView 使用不同高度的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19520040/

相关文章:

objective-c - 我如何多次调用一个函数,每次调用它时都会改变函数内部的随机数?

ios - 如何获取指定单元格周围的单元格索引?

ios - 如何从应用程序更新 iOS 14 Widget 背景颜色?

ios - 合并托管对象上下文的方法

objective-c - addSubview:方法非常慢

ios - IOS中NSPicturesDirectory的用途

ios - UICollectionView insertItemsAtIndexPaths : seems to reload collectionview or autoscrolls to top

ios - 在 UICollectionView swift 中获取单元格 onClick 的所有 subview

ios - 无法显示简单的 CAGradientLayer

iphone - 如何将下载的视频文件保存到 Objective C 中的图片库中?