Adding UIButton to UITableView section header

Viewed 37576

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

Swift 4 :

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

    let frame = tableView.frame
    let button = UIButton(frame: CGRect(x: 5, y: 10, width: 15, height: 15))
    button.tag = section
    button.setImage(UIImage(named: "remove_button"), for: UIControl.State.normal)
    button.addTarget(self,action:#selector(buttonClicked),for:.touchUpInside)

    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
    headerView.addSubview(button)

    return headerView
}

This functions handles the button click:

@objc func buttonClicked(sender:UIButton)
{
    if(sender.tag == 1){

       //Do something for tag 1
    }
    print("buttonClicked")
}
Related