iphone - UITableView 具有两种类型的单元格

标签 iphone ios uitableview

enter image description here

假设

UITableView 包含 50 行。第一行包含一个项目,每个偶数行索引单元格包含两个项目? 为此,我们需要为每个备用行使用两个 XIB View ?

totalrowcount 和 cellAtRowatindexpath 逻辑的逻辑是什么?

还有其他选择吗?

最佳答案

我想你的 table 看起来像这样:

+---------------------+
|        Data 1       |  --> Cell Type 1
+---------------------+
|  Data 2  |  Data 3  |  --> Cell Type 2
+---------------------+
|        Data 4       |
+---------------------+
|  Data 5  |  Data 6  |
+---------------------+
.         ...         .

首先,您应该为这些单元格类型设计两个不同的 UITableViewCell nib。就我个人而言,我会使用 Storyboard,设计两个具有不同标识符的动态单元格,并在需要时调用它们。例如:

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                              reuseIdentifier:@"Cell Type 1"];

让我们来看看tableView的数据源方法。我假设数据存储在名为 self.tableData 的数组中。您可以构建一个返回行数的逻辑,如下所示:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ceil([self.tableData count]*(2.0f/3.0f));
}

然后在您的 cellForRowAtIndexPath 方法中,返回这些单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    NSUInteger objectIndex = floor(indexPath.row*(3.0f/2.0f));

    if (indexPath.row % 2 == 0) {
        // define cell as Cell Type 1 from nib
        cell.yourLabel.text = [self.tableData objectAtIndex:objectIndex];
    } else {
        // define cell as Cell Type 2 from nib
        cell.yourLabel1.text = [self.tableData objectAtIndex:objectIndex];
        cell.yourLabel2.text = [self.tableData objectAtIndex:(objectIndex+1)];
    }

   return cell;
}

请注意,我假设您的 tableData 数组包含类似 NSString 对象的内容,并且您的单元格上有 UILabel 。上面的代码从相应索引的数据源中获取对象并填充标签。

关于iphone - UITableView 具有两种类型的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813734/

相关文章:

ios - 关闭我添加的 View 后 UITableView 单元格消失

ios - 我应该使用 UITableView 节标题还是静态 UITableViewCell?

iOS UITableView : clear section button

java - 如何使用 Java 向 iPhone 发送推送通知消息?

iphone - 如何在 Xcode 调试器中查看对象内的值?

ios - 为 iOS 布局添加相对约束

ios - 如何在 swift 中创建动态 UItextfields?

ios - 当视频在 WebView 中播放时,在 iOS (Swift) 中向 AVPlayer 添加 UIButton

iphone - UICollectionView 中的大单元格在单元格仍显示时被删除

ios - 执行 expo build :ios 时,Apple Developer Portal 中的身份验证失败