Adding UIButton to UITableView section header

前端 未结 7 1146
一个人的身影
一个人的身影 2021-02-01 20:20

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.

7条回答
  •  死守一世寂寞
    2021-02-01 20:59

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

提交回复
热议问题