iosuitableviewuibuttonuilabelnstableheaderview

Need to add multiple UI elements to tableheaderview of UITable in iOS


I have a UITableViewController that has a tableView. To this tableView, I would like to add both a label as well as a button but unfortunately, I am only able to add one or the other.

Here is my code that I am working with:

- (void) viewDidLoad {

    [super viewDidLoad];

    selectAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [selectAllButton setFrame:CGRectMake(280, 0, 25, 25)];
    [selectAllButton setImage:[UIImage imageNamed:@"CheckBox1.png"] forState:UIControlStateSelected];
    [selectAllButton setImage:[UIImage imageNamed:@"CheckBox2.png"] forState:UIControlStateNormal];
    [selectAllButton setUserInteractionEnabled:YES];
    [selectAllButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];

    selectAllLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 40)];
    [selectAllLabel setTextColor:[UIColor blackColor]];
    [selectAllLabel setBackgroundColor:[UIColor clearColor]];
    [selectAllLabel setText:@"Select All"];

    self.tableView.tableHeaderView = selectAllButton;
    self.tableView.tableHeaderView = selectAllLabel;

}

When I run the above method, I am only able to see my label which tells me it is replacing the button. Is there a way for me to get both elements to appear in the tableheaderview?


Solution

  • Create a UIView, add your button & label to it as subviews, than make that view your self.tableview.tableHeaderView

    ...your code
    UIView *headerView = [UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, selectAllButton.frame.size.height + selectAllLabel.frame.size.height)];
    
    [headerView addSubview:selectAllButton];
    [headerView selectAllLabel];
    
    self.tableView.tableHeaderView = headerView;
    

    When you init your button & label be sure to change the frame as they will be based on the UIView