Customize UITableView header section Customize UITableView header section swift swift

Customize UITableView header section


You can try this:

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];    /* Create custom view to display section header... */    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];    [label setFont:[UIFont boldSystemFontOfSize:12]];     NSString *string =[list objectAtIndex:section];    /* Section header is in 0th index... */    [label setText:string];    [view addSubview:label];    [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...    return view;}


The selected answer using tableView :viewForHeaderInSection: is correct.

Just to share a tip here.

If you are using storyboard/xib, then you could create another prototype cell and use it for your "section cell". The code to configure the header is similar to how you configure for row cells.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {    static NSString *HeaderCellIdentifier = @"Header";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier];    if (cell == nil) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier];    }    // Configure the cell title etc    [self configureHeaderCell:cell inSection:section];    return cell;}


Swift version of Lochana Tejas answer:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {    let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))    let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))    label.font = UIFont.systemFontOfSize(14)    label.text = list.objectAtIndex(indexPath.row) as! String    view.addSubview(label)    view.backgroundColor = UIColor.grayColor() // Set your background color    return view}