Một cách khác để làm điều này sẽ là đáp ứng với UITableViewDelegatephương pháp willDisplayHeaderView. Quan điểm đã thông qua thực sự là một ví dụ của a UITableViewHeaderFooterView.
Ví dụ dưới đây thay đổi phông chữ và cũng căn giữa văn bản tiêu đề theo chiều dọc và chiều ngang trong ô. Lưu ý rằng bạn cũng nên phản hồi để heightForHeaderInSectioncó bất kỳ thay đổi nào đối với chiều cao của người đứng đầu của bạn được tính trong bố cục của chế độ xem bảng. (Đó là, nếu bạn quyết định thay đổi chiều cao tiêu đề trong willDisplayHeaderViewphương pháp này .)
Sau đó, bạn có thể trả lời titleForHeaderInSectionphương thức để sử dụng lại tiêu đề được định cấu hình này với các tiêu đề phần khác nhau.
Mục tiêu-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.textColor = [UIColor redColor];
header.textLabel.font = [UIFont boldSystemFontOfSize:18];
CGRect headerFrame = header.frame;
header.textLabel.frame = headerFrame;
header.textLabel.textAlignment = NSTextAlignmentCenter;
}
Swift 1.2
(Lưu ý: nếu trình điều khiển xem của bạn là hậu duệ của a UITableViewController, thì điều này cần phải được khai báo là override func.)
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
header.textLabel.font = UIFont.boldSystemFontOfSize(18)
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Center
}
Swift 3.0
Mã này cũng đảm bảo rằng ứng dụng không gặp sự cố nếu chế độ xem tiêu đề của bạn không phải là UITableViewHeaderFooterView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textColor = UIColor.red
header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
header.textLabel?.frame = header.frame
header.textLabel?.textAlignment = .center
}