添加iOS UITableView HeaderView(不是节标题)

Ass*_*f b 166 iphone uitableview ios

我想在联系人应用程序中添加一个表头(不是节头),例如: 在此输入图像描述

就像那样 - 桌子上方图像旁边的标签.

我希望所有视图都可以滚动,所以我不能把它们放在桌子之外.

我怎样才能做到这一点?

pet*_*rjb 245

UITableViewtableHeaderView房产.将其设置为您想要的任何视图.

使用new UIView作为容器,将文本标签和图像视图添加到新的容器中UIView,然后设置tableHeaderView为新视图.

例如,在UITableViewController:

-(void)viewDidLoad
{
     // ...
     UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:imageView];
     UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:labelView];
     self.tableView.tableHeaderView = headerView;
     [imageView release];
     [labelView release];
     [headerView release];
     // ...
} 
Run Code Online (Sandbox Code Playgroud)


Kir*_*odd 192

您可以在Interface Builder中轻松完成.只需使用表创建一个视图,然后将另一个视图放到表中.这将成为表头视图.将标签和图像添加到该视图.有关视图层次结构,请参见下面的图片. 在Interface Builder中查看层次结构

  • 我更喜欢这个答案,因为当我能整齐地设置代码并将其放在IB中时,为什么要编写代码 (11认同)
  • 值得一提的是它现在如何在StoryBoard编辑器中运行:http://stackoverflow.com/q/7841167/926907 (2认同)

Kin*_*ard 13

Swift中:

override func viewDidLoad() {
    super.viewDidLoad()

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter
}
Run Code Online (Sandbox Code Playgroud)


ian*_*ari 11

您也可以简单地在"界面"构建器中创建一个UIView,然后拖放ImageView和UILabel(使其看起来像您想要的标题),然后使用它.

一旦你的UIView看起来也像你想要的那样,你可以通过编程从XIB初始化它并添加到你的UITableView.换句话说,您不必在IB中设计ENTIRE表.只是headerView(这样头文件视图也可以在其他表中重用)

例如,我有一个自定义UIView用于我的一个表头.该视图由名为"CustomHeaderView"的xib文件管理,并使用我的UITableViewController子类中的以下代码将其加载到表头中:

-(UIView *) customHeaderView {
    if (!customHeaderView) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
    }

    return customHeaderView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set the CustomerHeaderView as the tables header view 
    self.tableView.tableHeaderView = self.customHeaderView;
}
Run Code Online (Sandbox Code Playgroud)