Iowa15 Iowa15 - 1 year ago 436
iOS Question

Adding UIButton to UITableView section header

I have a

with 1 section and for the section header, I would like to keep everything about the header the same but simply add a button on the right side. I cannot put the button in the navigation controller because the two available spots to put such a button are already occupied by other buttons.

Here you can see the result of what I tried to do. Now all I want to do is put an add button on the right side of the header, but what I have tried didn't work. I also tried some other solutions on StackOverflow, but they did not accomplish quite what I wanted to do. Additionally, if there is a better way of creating an add button, please let me know. I tried using a
but I couldn't figure out how to add its view to an actual view. Thanks!

enter image description here

This is what I have so far in my delegate:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
UIButton *addButton = [[UIButton alloc] init]; //I also tried setting a frame for the
button, but that did not seem to work, so I figured I would just leave it blank for posting
the question.
addButton.titleLabel.text = @"+";
addButton.backgroundColor = [UIColor redColor];
[self.tableView.tableHeaderView insertSubview:addButton atIndex:0];
//I feel like this is a bad idea

return self.tableView.tableHeaderView;

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
return 50;

Answer Source

The problem is that your self.tableView.tableHeaderView is nil at this point in time, therefore you can't use it. So what you need to do is, create a UIView, add title, and button to it, style them, and return it.

This should add a title and button to your section header, you still need to style the title with correct font and size but will give you an idea.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGRect frame = tableView.frame;

    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
    [addButton setTitle:@"+" forState:UIControlStateNormal];
    addButton.backgroundColor = [UIColor redColor];

    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    title.text = @"Reminders";

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [headerView addSubview:title];
    [headerView addSubview:addButton];

    return headerView;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download