假设
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/