【问题标题】:Display different cells based on data type in UICollectionView根据 UICollectionView 中的数据类型显示不同的单元格
【发布时间】:2015-05-13 07:05:08
【问题描述】:

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

【问题讨论】:

  • 由于缺乏声誉,我无法分享单元格图像。
  • 对你有好处。你打算用这些细胞做什么?
  • 你可以在这里发布你的图片postimage.org
  • 我想使用单元格来显示基于服务器数据的包含内容,那么我如何知道要显示哪个单元格
  • 点赞 Facebook 帖子类型单元格

标签: ios objective-c uicollectionview


【解决方案1】:

首先,您为单元格注册布局的 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;
}

【讨论】:

  • 感谢您回答我的问题,我买了我在情节提要中创建的单元格,将项目数设为 3,并为每个单元格提供不同的标识符
  • 那么你可以省略registerNib调用。其他代码还是可以的
【解决方案2】:

你可以使用

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

【讨论】:

  • 三种不同大小、不同布局的单元格
猜你喜欢
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2014-11-07
  • 1970-01-01
相关资源
最近更新 更多