UITableView 的每個 Section 上下都可以各自附加一段說明文字,也就是頁眉(header)與頁腳(footer)。它們常用來標示分組名稱、補充說明或放置提示資訊。設定方式非常直覺,只要實作對應的 dataSource 方法即可。本文以分組樣式的表格示範如何為第一個 Section 加上頁眉與頁腳。
ZYViewHeaderFooterController.h:
#import <UIKit/UIKit.h> @interface ZYViewHeaderFooterController : UIViewController<UITableViewDelegate,UITableViewDataSource> @property(nonatomic,strong) UITableView *myTableView; @end
ZYViewHeaderFooterController.m:
@synthesize myTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// 頁眉頁腳在分組樣式下呈現最自然
myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
self.myTableView.delegate = self;
myTableView.dataSource = self;
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:myTableView];
}
// 每個 Section 的行數
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 3;
}
// 每行的數據
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *result = nil;
if ([tableView isEqual:myTableView]) {
static NSString *tableViewCellIdentifier = @"MyCells";
result = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier];
if (result == nil) {
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:tableViewCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld,Cell %ld",
(long)indexPath.section, (long)indexPath.row];
}
return result;
}
// 設定 Section 的頁眉文字
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *result = nil;
if ([tableView isEqual:myTableView] && section == 0) {
result = @"Section 0 Header";
}
return result;
}
// 設定 Section 的頁腳文字
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
NSString *result = nil;
if ([tableView isEqual:myTableView] && section == 0) {
result = @"Section 0 Footer";
}
return result;
}
回傳 nil 就代表該 Section 不顯示頁眉或頁腳,因此這個方法可以精細控制到「哪一段要顯示、哪一段不顯示」的程度。
如果需要的不是一行純文字,而是更複雜的排版——例如帶圖示的標題、可點擊的說明區塊——可以改用 viewForHeaderInSection: 與 viewForFooterInSection:,回傳任意 UIView 即可,並搭配 heightForHeaderInSection: 指定高度。兩組方法的差別在於「文字 vs 視圖」,前者省事,後者自由。
第一個 Section 的上下方各自出現了對應的說明文字,其餘 Section 因回傳 nil 而保持乾淨,正是我們預期的效果。