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.
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;
}
If you want to use Interface Builder to build your section header, you can use a UITableViewCell
as the header. Create a prototype cell for your header in your UITableView, customize as you would any other cell, including adding labels, buttons, and constraints.
You can instantiate in your UITableViewController lazily:
lazy var headerCell: MyHeaderTableViewCell = {
let cell = tableView.dequeueReusableCell(withIdentifier: "Header") as! MyHeaderTableViewCell
return cell
}()
To make it the header:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerCell
}
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;
}
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")
}
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.
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];
}
}