Adding UIButton to UITableView section header

37,370

Solution 1

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

Solution 2

From iOS 6, you can also implement

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

in your UITableViewDelegate. For example:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if (section == 0) {
        if ([view.subviews.lastObject isKindOfClass:[UIButton class]]) {
            return;
        }
        UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(view.frame.size.width - 160.0, 0, 160.0, view.frame.size.height); // x,y,width,height
        [button setTitle:@"My Button" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(sectionHeaderButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
}

Solution 3

If you are interested in Swift solution:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let frame = tableView.frame

    let button = UIButton(frame: CGRectMake(5, 10, 15, 15))  // create button
    button.tag = section 
    // the button is image - set image
    button.setImage(UIImage(named: "remove_button"), forState: UIControlState.Normal)  // assumes there is an image named "remove_button"
    button.addTarget(self, action: #selector(TestController.remove(_:)), forControlEvents: .TouchUpInside)  // add selector called by clicking on the button

    let headerView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))  // create custom view
    headerView.addSubview(button)   // add the button to the view

    return headerView   
}

You might want to specify the height of the header in the section. This must be in sync with the height of the custom view:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat(30)
}

Solution 4

You have 2 choices, both via your tableView.delegate. The first involves implementing the delegate method

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

which enables you to basically return anything you want in a custom view, which will be used as the header for your desired section. This could be as simple as

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [addButton addTarget:self action:@selector(SomeMethod:) forControlEvents:UIControlEventTouchUpInside];
    return addButton;
}

which will put a round info button (centered) as your header. But more likely you'll want to create an actual UIView object and populate it with your button (and a section title label?) and lay everything out as you like [see others' answers for how to do this].

However, the second approach is probably better for the general case of simply adding a button to (one of) your section headers [I know you stated 1 section, but a lot of folks will probably land on this question wanting to do similar in a multi-section table]. This involves implementing the delegate method

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

and basically adding your button to the header after-the-fact; specifically

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Remove old button from re-used header
    if ([view.subviews.lastObject isKindOfClass:UIButton.class])
        [view.subviews.lastObject removeFromSuperview];

    if (section == MySectionNumberWithButton) {
        UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [addButton addTarget:self action:@selector(SomeMethod:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:addButton];

        // Place button on far right margin of header
        addButton.translatesAutoresizingMaskIntoConstraints = NO; // use autolayout constraints instead
        [addButton.trailingAnchor constraintEqualToAnchor:view.layoutMarginsGuide.trailingAnchor].active = YES;
        [addButton.bottomAnchor constraintEqualToAnchor:view.layoutMarginsGuide.bottomAnchor].active = YES;
    }
}

Note, because the tableView re-uses headers, in a multi-section table you must make sure to remove any button you might have previously added, otherwise you'll eventually end up with buttons in unwanted sections. Then, if this is the right section, add the button to the existing header. Note, I'm using NSLayoutAnchor (iOS 9+) to layout the button for brevity; you can do the same with NSLayoutConstraint (iOS 6+)

This approach has the distinct advantage that - for just adding a button - you dont have to recreate the regular layout to match all your other (non-button) headers, or worry about margins changing when you rotate your device, etc. In particular, the header title is untouched and will retain any global appearance settings you may have defined for table headers (eg font, color, ...), all of which you'd have the messy job of re-creating if you took the tableView:viewForHeaderInSection: approach.

Solution 5

You can do that by using the below code, you can put any type of view in header view but you have to specify the frame for it.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc]init];
    UIButton *addButton=[UIButton buttonWithType:UIButtonTypeContactAdd];
    addButton.frame=CGRectMake(250, 0, 100, 50);
    [view addSubview:addButton];
    [tblView.tableHeaderView insertSubview:view atIndex:0];
    //I feel like this is a bad idea

    return view;
}
Share:
37,370

Related videos on Youtube

Iowa15
Author by

Iowa15

Hi, I am a self taught programmer just finishing high school. Right now, I am mainly focused on app development. Check out my work here: https://itunes.apple.com/us/artist/ajay-penmatcha/id823193715

Updated on August 31, 2020

Comments

  • Iowa15
    Iowa15 over 3 years

    I have a UITableView 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 UIBarButtonItem 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;
    }
    
  • Alex Sorokoletov
    Alex Sorokoletov over 9 years
    For some reason, this code produces correct view (picture) but button does not react to touches :(
  • Yas Tabasam
    Yas Tabasam over 9 years
    @AlexSorokoletov - Please make sure your button is not outside of its parent frame.
  • Alex Sorokoletov
    Alex Sorokoletov over 9 years
    It is not, TouchUpInside/TouchDownInside events are raised, but no visual animation on the button
  • Yas Tabasam
    Yas Tabasam over 9 years
    @AlexSorokoletov - in that case you need to change the button style for highlighted and/or selected state.
  • Alex Sorokoletov
    Alex Sorokoletov over 9 years
    can you please elaborate? I'm not sure I know how to do that and will be grateful for any help
  • onnoweb
    onnoweb about 9 years
    You need to add a target to the button.
  • tatiana_c
    tatiana_c about 8 years
    you saved my life with check of lastObject
  • Sterling Christensen
    Sterling Christensen almost 8 years
    @AlexSorokoletov Use [addButton setTitle:@"+" forState:UIControlStateNormal]; instead of addButton.titleLabel.text = @"+";. That's probably why it doesn't animate.
  • Grimxn
    Grimxn about 7 years
    Great answer! And a neat & painless intro to NSLayoutAnchor, which I have avoided until now. Suggest adding addButton.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.centerYAnchor).isActive = true as an alternative!
  • Nostradamus
    Nostradamus over 4 years
    FYI I needed to use: let headerView = UITableViewHeaderFooterView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 60))
  • Robert Schmid
    Robert Schmid over 4 years
    I love this answer. It is exactly what I wanted.