免费开源的iOS开发学习平台

UITableView详解:16-UITableView的Header与Footer

每一个UITableView对象都有一个tableHeaderView属性和一个tableFooterView属性,这两个属性是对应整个表视图的顶部视图和底部视图。需要注意同Section的HeaderView以及FooterView进行区分。通常来说,UITableView的tableHeaderView经常会放置搜索栏或者图片轮播器,tableFooterView也可以根据设计需要添加定制的视图类UIView类控件,例如设置成为上拉刷新按钮。

UITableView的Header与Footer设置

UITableView的顶部视图和底部视图要通过属性tableHeaderViewtableFooterView来设置。

@property (nonatomic, strong, nullable) UIView *tableHeaderView;              
@property (nonatomic, strong, nullable) UIView *tableFooterView;

由于这两个属性都是UIView类型的,因此其定制能力非常强大,我们可以把任意UIView类以及其子类对象设置为表视图的顶部视图以及底部视图。在下方的代码中,我们可以自定义两个简单的矩形UIView作为验证使用,绿色的View为tableHeaderView,黄色的的View为tableFooterView。

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        //UITableView的顶部视图
        UIView *tableViewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
        tableViewHeader.backgroundColor = [UIColor greenColor];
        _tableView.tableHeaderView = tableViewHeader;
        //UITableView的底部视图
        UIView *tableViewFooter = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
        tableViewFooter.backgroundColor = [UIColor yellowColor];
        _tableView.tableFooterView = tableViewFooter;
    }
    return _tableView;
}

示例代码

https://github.com/99ios/8.2.16