3lvis
3lvis

Reputation: 4180

How to get the header view of a grouped table view?

I want to get all the views of a grouped table view to change the label color and to set the background color.

Upvotes: 0

Views: 858

Answers (3)

João Nunes
João Nunes

Reputation: 3761

You also need to add the textColor:

 label.textColor = [UIColor colorWithRed:0.265 green:0.294 blue:0.367 alpha:1.000];

Upvotes: 0

3lvis
3lvis

Reputation: 4180

I found the answer, it's not possible to get the header view of a table view section. But you can implement the delegate tableView:viewForHeaderInSection: to recreate the header view and the label. The following code will give you the same header view and the exact label.

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

    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];

    if (sectionTitle == nil) {
        return nil;
    }

    // Create label with section title
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 5.5f, 300.0f, 30.0f)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:16.5];
    label.shadowColor = [UIColor whiteColor];
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    label.text = sectionTitle;

    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)];
    view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    [view addSubview:label];

    return view;
}

Upvotes: 2

Rob
Rob

Reputation: 437422

That's great you figured out your solution.

A couple of suggestions:

  1. Don't hardcode the CGRect for the width of your frame, but rather use self.view.size.width for the width (e.g. in case you're in landscape orientation or if Apple ever introduces an iPhone with a different screen size);

  2. You probably want to use autoresizingMask for both the label and the view that holds the label, so that they'll resize as the screen orientation changes, or make sure you invoke [self.tableview reloadData] on orientation changes; and

  3. This is obviously a single line label ... if that works for you great, otherwise you'd want to use sizeWithFont:constrainedToSize:lineBreakMode to determine the height, both for creating the label/view as well as responding to tableView:heightForHeaderInSection:.

Upvotes: 0

Related Questions