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

Display different cells based on data type in UICollectionView

我在 UICollectionview 中有三种不同类型的单元格,它们具有不同的 content size(包含 imagelabelbutton)。我正在从 Web 服务获取数据。我想根据这些类型显示正确的单元格。

你可以使用

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

注:indexpath

例如。将所有图像添加到 array.

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;
}

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

[collectionView registerNib:myCellTypeImageNib forCellWithReuseIdentifier:@"MyModelTypeImageCellIdentifier"];
[collectionView registerNib:myCellTypeLabelNib forCellWithReuseIdentifier:@"MyModelTypeLabelCellIdentifier"];
[collectionView registerNib:myCellTypeButtonNib forCellWithReuseIdentifier:@"MyModelTypeButtonCellIdentifier"];

然后 return 他们适当地:

- (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;
}