Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding UIButton to UITableView section header

Tags:

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; } 
like image 605
Iowa15 Avatar asked Dec 26 '13 21:12

Iowa15


1 Answers

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; } 
like image 79
Yas Tabasam Avatar answered Oct 04 '22 11:10

Yas Tabasam