出于性能考虑,通常会重用 UITableView 的单元格。 有没有办法对 TableView 标题 View 执行相同的操作? 我说的是那些用委托(delegate)方法返回的:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
我尝试执行以下操作,但似乎没有按预期工作:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static NSString *CellIdentifier = @"Header";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
cell = [self getHeaderContentView: CellIdentifier];
}
return cell;
}
有没有办法重用标题 View ?
最佳答案
Apple 内置重用 tableview 单元格的功能的原因是,虽然 tableview 可能有很多行,但屏幕上只显示少数行。应用程序可以重用现有的单元并根据需要重新配置它们,而不是为每个单元分配内存。
首先,标题 View 只是 UIView,虽然 UITableViewCell 是 UIView 的子类,但它们并不打算放置为节标题的 View 。
此外,由于节标题通常比总行数少得多,因此没有理由构建可重用性机制,事实上 Apple 还没有为通用 UIView 实现可重用性机制。
请注意,如果您只是为标题设置标签,则可以使用 -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
代替。
对于更自定义的内容,例如带有红色文本的标签(或按钮、图像等),您可以执行以下操作:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 44)] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:headerView.frame] autorelease];
label.textColor = [UIColor redColor];
label.text = [NSString stringWithFormat:@"Section %i", section];
[headerView addSubview:label];
return headerView;
}
关于iphone - 可重用的 TableView 标题 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/960119/