IOS_設定UITableView Section的背景顏色和字型顏色(自定義section佈局)
阿新 • • 發佈:2019-01-22
section所顯示的灰色背景和白色字型是預設的,呼叫以下方法即可實現
要改變高度,需要重寫:
- (CGFloat)tableView:(UITableView *)tableViewheightForHeaderInSection:(NSInteger)section{
return30;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [self.keys objectAtIndex:section];
}
如果想改變此處的背景與字型的話,官方沒有開放介面去直接修改以上兩個屬性,所以,只有自己加Label,加View去實現,程式碼如下:
實現委託方法- (UIView*)tableView:(UITableView*)tableViewviewForHeaderInSection:(NSInteger)section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView* myView = [[[UIView alloc] init] autorelease]; myView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7]; UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)]; titleLabel.textColor=[UIColor whiteColor]; titleLabel.backgroundColor = [UIColor clearColor]; titleLabel.text=[self.keys objectAtIndex:section]; [myView addSubview:titleLabel]; [titleLabel release]; return myView; }
需要注意的一點是:這個方法裡返回檢視的大小是固定不變的
Thetable view automatically adjusts the height of the section headerto accommodate the returned view object. The table view does notcall this method if it was created in a plain style(UITableViewStylePlain).要改變高度,需要重寫:
- (CGFloat)tableView:(UITableView *)tableViewheightForHeaderInSection:(NSInteger)section{
return30;
}