我在弄清楚如何在UITableView中显示不同的单元格样式以及自定义单元格时遇到了问题。我理解如何设置和放置单元格以及构建基本的UITableView,但不知道如何在一个单元中“混合和匹配”单元格。
我可以向您展示我想要实现的最好的例子是Tweetie 2应用程序。
段的顶部有一个块段,然后在它下面有UITableViewCell的UITableViewCellStyleValue2样式集。我究竟该如何实现这种效果?
提前致谢
答案 0 :(得分:8)
主要布局是分组表。每个单元簇都是一个表格部分。最顶部的单元格设置为透明背景。
使这项工作的关键是在tableview委托中有一个逻辑结构,它可以理解哪个单元格布局在哪个部分和哪个行中。 switch语句通常最简单,尽管您也可以使用数组或字典configure来反映布局。
所以,在tableView:cellForRowAtIndexPath:
中你会有类似的东西:
switch (indexPath.section) {
case 0:
cell= //configure cell with transparent background
break;
case 1:
if (indexPath.row==0) {
cell = // configure cell for multiline
}else {
cell = // configure for UITableViewCellStyleValue2
}
break;
case 2:
// .. and so on for each section and cell
break;
default:
break;
}
在这种布局中,tableview被用作逻辑表(显示列表结构化数据的重复单元),而不是用作管理布局的便利机制。管理tableview的逻辑必须更复杂,并反映布局的需要。
答案 1 :(得分:4)
最直接的方法是将-tableView:cellForRowAtIndexPath:
的实施更改为使用indexPath.section
和indexPath.row
来确定要绘制的单元格类型。例如:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
if (indexPath.row == 0) {
// return long text style cell
} else {
// return left/right label style cell
}
} else {
// return the 4-way button style cell
}
}
根据您渲染的细胞数量以及您获得的细胞样式数量,您可能需要重复使用细胞,在这种情况下,您应该为每种细胞样式使用不同的细胞标识符。
答案 2 :(得分:1)
这是一种优雅的方式:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
/*
Call a function to create all custom cells.
Send the tableview and the indexPath to this function.
So, your code will be clean and easy to read an maintenance =D
DON'T forget to change the height of each cell
*/
if (indexPath.row < 3)
return [self createACustomCell1:tableView indexPath:indexPath];
else
return [self createACustomCell2:tableView indexPath:indexPath];
}
//*************
// Create CUSTOM CELL 2
//*************
-(UITableViewCell *)createACustomCell1:(UITableView *)anTableView indexPath:(NSIndexPath *)indexPath{
static NSString *CUSTOMCELL_1 = @"CUSTOMCELL_1";
CustomCell_1 *cell = [anTableView dequeueReusableCellWithIdentifier:CUSTOMCELL_1];
if (!cell){
[anTableView registerNib:[UINib nibWithNibName:CUSTOMCELL_1
bundle:nil] forCellReuseIdentifier:CUSTOMCELL_1];
cell = [anTableView dequeueReusableCellWithIdentifier:CUSTOMCELL_1];
}
// Cell customization above
return cell;
}
//*************
// Create CUSTOM CELL 2
//*************
-(UITableViewCell *)createACustomCell2:(UITableView *)anTableView indexPath:(NSIndexPath *)indexPath{
static NSString *CUSTOMCELL_2 = @"CUSTOMCELL_2";
CustomCell_2 *cell = [anTableView dequeueReusableCellWithIdentifier:CUSTOMCELL_2];
if (!cell){
[anTableView registerNib:[UINib nibWithNibName:CUSTOMCELL_2
bundle:nil] forCellReuseIdentifier:CUSTOMCELL_2];
cell = [anTableView dequeueReusableCellWithIdentifier:CUSTOMCELL_2];
}
// Cell customization above
return cell;
}
答案 3 :(得分:0)
要获得与Tweetie拆分单元相同的效果,请创建自定义单元格并添加分段控件并创建标题和详细信息标签