Ios 根据UICollectionView中的数据类型显示不同的单元格

Ios 根据UICollectionView中的数据类型显示不同的单元格,ios,objective-c,uicollectionview,Ios,Objective C,Uicollectionview,我在UICollectionview中有三种不同类型的单元格,它们的内容大小不同(包含图像、标签和按钮)。我正在从web服务获取数据。我想根据这些类型显示正确的单元格。您可以使用 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 注意:indepath 比如说。将所有图像添加到数组中 self.my

我在
UICollectionview
中有三种不同类型的单元格,它们的
内容大小不同(包含
图像
标签
按钮
)。我正在从web服务获取数据。我想根据这些类型显示正确的单元格。

您可以使用

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
注意:
indepath

比如说。将所有图像添加到
数组中

self.myArray = [[NSArray alloc] initWithObjects:@"first.jpg",
                                 @"second.jpg",
                                 @"third.jpg",
                                 @"last.jpg",nil]
然后在
cellForRow…
中执行以下操作:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // configure cell
    ...
    cell.myImageView = [self.myArray objectAtIndex:indexPath.row;
}

首先,为单元格注册布局的NIB:

[collectionView registerNib:myCellTypeImageNib forCellWithReuseIdentifier:@"MyModelTypeImageCellIdentifier"];
[collectionView registerNib:myCellTypeLabelNib forCellWithReuseIdentifier:@"MyModelTypeLabelCellIdentifier"];
[collectionView registerNib:myCellTypeButtonNib forCellWithReuseIdentifier:@"MyModelTypeButtonCellIdentifier"];
然后将其适当退回:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyModel *modelObject = self.dataArray[indexPath.item];
    UICollectionViewCell *cell = nil;
    switch (modelObject.type) {
        case MyModelTypeImage:
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyModelTypeImageCellIdentifier" forIndexPath:indexPath];
            //adjust cell
            break;
        case MyModelTypeLabel:
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyModelTypeLabelCellIdentifier" forIndexPath:indexPath];
            //adjust cell
            break;
        case MyModelTypeButton:
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyModelTypeButtonCellIdentifier" forIndexPath:indexPath];
            //adjust cell
            break;
    }
    return cell;
}

由于缺乏声誉,我无法分享手机图像。对你有好处。你打算用这些单元格做什么?你可以在这里发布你的图像我想用这个单元格来显示基于服务器数据的内容,那么我怎么知道要显示哪个单元格像Facebook post类型的单元格三个不同大小、不同布局的单元格谢谢回答我的问题,我购买了我在故事板中创建的单元,将项目数设为3,并为每个单元指定不同的标识符,然后您可以省略
registernb
调用。其他代码仍然可以