iosobjective-cswiftuitableviewuitableviewsectionheader

Changing Font Size For UITableView Section Headers


Can someone please instruct me on the easiest way to change the font size for the text in a UITableView section header?

I have the section titles implemented using the following method:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Then, I understand how to successfully change the section header height using this method:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

I have the UITableView cells populated using this method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

However, I'm stuck as to how to actually increase the font size - or for that matter the font style - of the section header text?

Can someone please assist? Thanks.


Solution

  • Unfortunately, you may have to override this:

    In Objective-C:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    

    In Swift:

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

    Try something like this:

    In Objective-C:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
        UILabel *myLabel = [[UILabel alloc] init];
        myLabel.frame = CGRectMake(20, 8, 320, 20);
        myLabel.font = [UIFont boldSystemFontOfSize:18];
        myLabel.text = [self tableView:tableView titleForHeaderInSection:section];
    
        UIView *headerView = [[UIView alloc] init];
        [headerView addSubview:myLabel];
    
        return headerView;
    }
    

    In Swift:

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        let myLabel = UILabel()
        myLabel.frame = CGRect(x: 20, y: 8, width: 320, height: 20)
        myLabel.font = UIFont.boldSystemFont(ofSize: 18)
        myLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
    
        let headerView = UIView()
        headerView.addSubview(myLabel)
    
        return headerView
    }