我需要一个与“设置”应用中的Twitter帐户类似的分组UITableView
:
也就是说,某种形式或菜单,其中某些部分具有预先知道的一组静态单元格,而其他一些部分必须是动态的,并且允许以与“添加帐户”相同的方式插入其他行。我在UITableView
文件中管理.xib
。对于静态单元格,我将.xib
个文件分开,我可以在视图控制器的cellForRowAtIndexPath:
方法中加载。
我该如何处理这种表?我找不到任何示例代码。
cellForRowAtIndexPath:
方法应该如何?我是否需要保留静态单元格的strong
属性?最好是在表视图所在的同一.xib
文件中直接设计每个静态单元格,并为它们设置出口? (虽然这不允许重用我的自定义单元格设计......)
我需要一些指导来实现这一目标并正确管理细胞和记忆。提前致谢
答案 0 :(得分:28)
如果只返回单元格而不在cellForRowAtIndexPath中添加任何内容,动态原型单元的行为就像静态单元格一样,因此您可以同时拥有“静态”单元格和动态单元格(行数和内容可变)使用动态原型。
在下面的示例中,我从IB中的表视图控制器开始(带有分组表视图),并将动态原型单元的数量更改为3.我将第一个单元的大小调整为80,并添加了UIImageView和两个标签。中间单元格是基本样式单元格,最后一个是具有单个居中标签的另一个自定义单元格。我给了他们每个人自己的标识符。这就是它在IB中的样子:
然后在代码中,我这样做了:
- (void)viewDidLoad {
[super viewDidLoad];
self.theData = @[@"One",@"Two",@"Three",@"Four",@"Five"];
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 1)
return self.theData.count;
return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0)
return 80;
return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
if (indexPath.section == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:@"TitleCell" forIndexPath:indexPath];
}else if (indexPath.section == 1) {
cell = [tableView dequeueReusableCellWithIdentifier:@"DataCell" forIndexPath:indexPath];
cell.textLabel.text = self.theData[indexPath.row];
}else if (indexPath.section == 2) {
cell = [tableView dequeueReusableCellWithIdentifier:@"ButtonCell" forIndexPath:indexPath];
}
return cell;
}
正如您所看到的,对于“静态”单元格,我只返回具有正确标识符的单元格,并且我得到了我在IB中设置的内容。运行时的结果看起来像是包含三个部分的已发布图像。
答案 1 :(得分:2)