Customize UITableView header section

268,104

Solution 1

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;
}

Solution 2

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;
}

Solution 3

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
}

Solution 4

If you use default header view you can only change the text on it with

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

For Swift:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

If you want to customize the view you need to create a new one your self.

Solution 5

why not use UITableViewHeaderFooterView?

Share:
268,104

Related videos on Youtube

limon
Author by

limon

Keen interest in mobile development. I like blocks. SOreadytohelp

Updated on June 03, 2021

Comments

  • limon
    limon almost 3 years

    I want to customize UITableView header for each section. So far, I've implemented

    -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    

    this UITabelViewDelegate method. What I want to do is to get current header for each section and just add UILabel as a subview.

    So far, I'm not able to accomplish that. Because, I couldn't find anything to get default section header. First question,is there any way to get default section header?

    If it's not possible, I need to create a container view which is a UIView but,this time I need to set default background color,shadow color etc. Because, if you look carefully into section's header, it's already customized.

    How can I get these default values for each section header?

    • borrrden
      borrrden about 11 years
      What's wrong with using tableView:titleForHeaderInSection: ?
    • limon
      limon about 11 years
      It returns a NSString, i need to set custom font so, i can't if i use tableView:titleForHeaderInSection:
    • Desdenova
      Desdenova about 11 years
      Or you can use images to mimic the default section headers. teehanlax.com/blog/ios-6-gui-psd-iphone-5
    • shallowThought
      shallowThought over 7 years
      @limon: How to implement section header: stackoverflow.com/a/32261262/1457385
  • limon
    limon about 11 years
    Yes, i can do that, but my question is how can i get default section header background,shadow value, the rest is easy to implement.
  • Lochana Ragupathy
    Lochana Ragupathy about 11 years
    thats your bg color watever color you want to set you can
  • Lochana Ragupathy
    Lochana Ragupathy about 11 years
    what do you mean by default section header background
  • cpprulez
    cpprulez about 11 years
    Well, the easiest would be to use the Digital Color Meter application to get the colors you want. Taking them by code would be tough, as far as I can tell...
  • limon
    limon about 11 years
    That's the issue, i've already done what you wrote. But, i don't know default background color of section header,which is kind of gray. But, i need it to be exactly default section header.
  • Lochana Ragupathy
    Lochana Ragupathy about 11 years
    hey come on use Digital color meter
  • shulmey
    shulmey almost 11 years
    make sure to set the UILabel's backgroundColor as well. I know I was slightly confused when my background wasn't turning clear for me.
  • Navnath Godse
    Navnath Godse almost 11 years
    Is it a tableView instead of tableview ?
  • SAHM
    SAHM over 10 years
    You can only use this if you do not also use -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section.
  • Gregzo
    Gregzo over 9 years
    Perfectly valid answer. Also, using UITableViewHeaderFooterView benefits from view recycling just like cells.
  • Nisha Gupta
    Nisha Gupta almost 9 years
    what is list in line NSString *string =[list objectAtIndex:section]; anybody can tell me
  • Kachi
    Kachi over 8 years
    there are a number of things wrong w/ this solution. First of which is the fact that if you implement "tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool", you'll notice that the section header will move along with the row when you slide. To avoid this, you must return cell.contentView instead. The Bigger issue is the fact that with this solution, the app will crash when you long press the section header. Correct way is to create a nib that extends UITableViewHeaderFooterView, register it w/ the tableview and return it in this method. Tested on iOS8
  • samwize
    samwize over 8 years
    @Kachi The solution is using viewForHeaderInSection not canEditRowAtIndexPath as you mentioned. I never verify the crash you said, but could you enlighten how a long press will cause a crash?
  • Kachi
    Kachi over 8 years
    what I meant was that if you implement this solution AND implement canEditRowAtIndexPath, you will see that the header will also slide with with the topmost row that you are deleting if you do not return cell.contentView. See this SO post: stackoverflow.com/questions/26009722/… The long press causes a crash because a message tries to get sent to a deallocated object. See this SO post: stackoverflow.com/questions/27622290/…
  • Fawkes
    Fawkes over 8 years
    @dmarsi I have found no evidence of them being deprecated.
  • CinCout
    CinCout over 8 years
    Mind elaborating your answer?
  • MSU_Bulldog
    MSU_Bulldog almost 8 years
    its [UIColor groupTableViewBackgroundColor];
  • theprojectabot
    theprojectabot about 7 years
    The header section wont show unless you specify with a method hook the 'height' of the section header. UITableView defaults to not showing headers if no height is specified. @CinCout
  • Boris Gafurov
    Boris Gafurov almost 7 years
    SectionHeaderTableViewCell - use of undeclared identifier
  • Anish Kumar
    Anish Kumar almost 7 years
    @BorisGafurov SectionHeaderTableViewCell is just an example name that I gave my UITableViewCell, which, I created in the storyboard.
  • Pratik Shah
    Pratik Shah almost 7 years
    how to make label height dynamic as per the text which is inside the view?
  • Vadim Bulavin
    Vadim Bulavin almost 7 years
    The override keyword is redundant. What is more, consider reusing header views rather than re-creating them.
  • raven_raven
    raven_raven over 6 years
    Please don't ever use UITableViewCell as a header view. You'll get very difficult to debug visual glitches - header will sometimes disappear because of how cells are dequeued and you'll be looking for hours why is that until you realize UITableViewCell does not belong in UITableView header.
  • Alex Zavatone
    Alex Zavatone over 6 years
    Using a UITableViewCell as a header is simply wrong.
  • Alex Zavatone
    Alex Zavatone over 6 years
    You don't need to cast it. You can just add what you want to the view. In fact, creating a new object will do nothing unless you assign it to view.
  • Craig Brown
    Craig Brown over 6 years
    @AlexZavatone That's right, you don't need to cast it if you're just adding views. It's helpful if you want to customise some of the default views like the text label.
  • Tyler A.
    Tyler A. over 5 years
    Why dequeueReusableCellWithIdentifier and not dequeueReusableHeaderFooterView?
  • GeneCode
    GeneCode over 4 years
    NGL, i copy pasted this code to my app and it works.
  • Felix Marianayagam
    Felix Marianayagam about 4 years
    Using this solution results in errors with either the cell being nil or the label inside it being nil. This seems to be a wrong solution.