UITableView - change section header color

前端 未结 30 2839
不思量自难忘°
不思量自难忘° 2020-11-27 08:50

How can I change color of a section header in UITableView?

EDIT: The answer provided by DJ-S should be considered for iOS 6 and above. The accepted

30条回答
  •  Happy的楠姐
    2020-11-27 09:16

    In iOS 7.0.4 I created a custom header with it's own XIB. Nothing mentioned here before worked. It had to be the subclass of the UITableViewHeaderFooterView to work with the dequeueReusableHeaderFooterViewWithIdentifier: and it seems that class is very stubborn regarding the background color. So finally I added an UIView (you could do it either with code or IB) with name customBackgroudView, and then set it's backgroundColor property. In layoutSubviews: I set that view's frame to bounds. It work with iOS 7 and gives no glitches.

    // in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
    // first child becomes contentView
    
    // in MyTableHeaderView.h
    @property (nonatomic, weak) IBOutlet UIView * customBackgroundView;
    
    // in MyTableHeaderView.m
    -(void)layoutSubviews;
    {
        [super layoutSubviews];
    
        self.customBackgroundView.frame = self.bounds;
    }
    // if you don't have XIB / use IB, put in the initializer:
    -(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
    {
        ...
        UIView * customBackgroundView = [[UIView alloc] init];
        [self.contentView addSubview:customBackgroundView];
        _customBackgroundView = customBackgroundView;
        ...
    }
    
    
    // in MyTableViewController.m
    -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        MyTableHeaderView * header = [self.tableView
                                              dequeueReusableHeaderFooterViewWithIdentifier:@"MyTableHeaderView"];
        header.customBackgroundView.backgroundColor = [UIColor redColor];
        return header;
    }
    

提交回复
热议问题