希望這個從UITableViewDelegate協議里得到的方法可以對你有所幫助:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];if (section == integerRepresentingYourSectionOfInterest)[headerView setBackgroundColor:[UIColor redColor]];else[headerView setBackgroundColor:[UIColor clearColor]];return headerView; }
使用任何你喜歡UIColor代替[UIColor redColor]。你可能還希望調整headerView的尺寸。
DoctorG
這是改變文本顏色的方法:
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];
whyoz
不要忘記從委托添加這段代碼,否則在某些情況下視圖將被切斷或者出現在table后面,相對于視圖/標簽的高度。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {return 30; }
Leszek ?arna
如果你想自定義header顏色,可以這樣做:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
這個方法在iOS 6.0.以上都很好用。
Maulik
這是在標題視圖添加圖片的方法:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease];headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);[headerView addSubview:headerImage];return headerView; }
William Jockusch
如果你不想建立自定義視圖,你也可以這樣改變顏色(需要在iOS6里):
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;UIView* content = castView.contentView;UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color herecontent.backgroundColor = color;} }
Dj S
這是常見的問題,我認為答案需要更新一下。
這個方法不涉及定義和創建自定義視圖。在iOS 6以上,你可以通過以下方法輕松改變背景色和文本色:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
委托方法
例如:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {// Background colorview.tintColor = [UIColor blackColor];// Text ColorUITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;[header.textLabel setTextColor:[UIColor whiteColor]];// Another way to set the background color// Note: does not preserve gradient effect of original header// header.contentView.backgroundColor = [UIColor blackColor]; }
orbv
通過UITableViewHeaderFooterView設置背景色的方法已經被廢棄了。請用contentView.backgroundColor代替。