4.9 Constructing Headers and Footers in Table Views

本文介绍如何在UITableView中实现自定义的Header和Footer视图,包括简单文本显示及使用UILabel等UIView组件,并调整其大小和位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建TableView的Header 和 Footer, 显示头部和尾部。
首先先来个简单的,送给急以求成的朋友。

如果你先在头部和尾部简单的显示一段文本,那个实现两个代理方法即可。
- (NSString *) tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section{
return @"Section 1 Header";
}
- (NSString *) tableView:(UITableView *)tableView
titleForFooterInSection:(NSInteger)section{
return @"Section 1 Footer";
}
好了,试试吧。

如果简单的文本不能满足你的需要,那么你就要按如下来实现了,不怕,其实一点都不麻烦,他可以把任何UIView显示在头部和尾部。
这里我们拿UILabel来举例,实现如下两个代理方法:

- (UIView *) tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section{

    UILabel * lbl = [[UILabel alloc] init];
    [lbl setText:@"I am the Header"];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl sizeToFit];
 return lbl;
}
- (UIView *) tableView:(UITableView*)tableViewviewForFooterInSection:(NSInteger)section{
 UILabel * lbl = [[UILabel alloc] init];
    [lbl setText:@"I am the Footer"];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl sizeToFit];
 return lbl;
}

运行程序我们发现Label显示出来了,但是显示得太窄了,而且紧挨着左边,这可不是我们想要的。
如何让他显示宽一点呢?代理,没错。
- (CGFloat) tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section{

return 30;
}
- (CGFloat) tableView:(UITableView *)tableView
heightForFooterInSection:(NSInteger)section{

return 30;
}

行高30足够我们显示刚才的饿Label了,OK,如何里面的文本不直接挨着左边呢?你是否和我一样想过在文本前面加上一些空格 ^-^

不过如果他不是Label,而是UIImageView,怎么办呢?
设置frame,设置x坐标加大点。可是一运行,发现根本行不通。
正确的解决办法是再创建一个UIView,然后把Label放在UIView上面,把UIView作为header and footer。OK,上代码
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel * lbl = [[UILabel alloc] init];
    [lbl setText:@"I am the Header"];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl sizeToFit];
   
    CGRect rect = [lbl frame];
    rect.origin.x += 10;
    rect.origin.y += 5;
   
    [lbl setFrame:rect];
   
    rect.size.width += 10;
   
    UIView * view = [[UIView alloc] initWithFrame:rect];
    [view addSubview:lbl];
   
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel * lbl = [[UILabel alloc] init];
    [lbl setText:@"I am the Footer"];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl sizeToFit];
   
    CGRect rect = [lbl frame];
    rect.origin.x += 10;
    rect.origin.y += 5;
   
    [lbl setFrame:rect];
   
    rect.size.width += 10;
   
    UIView * view = [[UIView alloc] initWithFrame:rect];
    [view addSubview:lbl];
   
    return view;
   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值