您的位置:首页 > 其它

4.9 Constructing Headers and Footers in Table Views

2013-11-28 12:15 429 查看
创建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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: