iphone - 可重用的 TableView 标题 View

标签 iphone cocoa-touch

出于性能考虑,通常会重用 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/

相关文章:

iphone - 我的 iPad 应用程序需要更多内存

iphone - 固有的 UIView 泄漏

iphone - 应用程序从后台进入前台

ios - 通过标题识别 UIAlertView,但不显示标题

ios - Xcode - 如何修复 'NSUnknownKeyException',原因 : … this class is not key value coding-compliant for the key X"error?

iphone - 制作 UIImage/UIScrollView 的一个区域 "clickable"

iphone - 如何将选定的数组从一个 uitable 传递到另一个 uitable

ios - 我如何在 iphone 的 objective c 中为短信和铃声设置振动?

Apple 代码中的 iPhone 内存泄漏

ios - Facebook 权限 - com.apple.accounts 错误 8