Changing Font Size For UITableView Section Headers

前端 未结 11 790
借酒劲吻你
借酒劲吻你 2020-12-12 09:28

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 t

11条回答
  •  醉话见心
    2020-12-12 10:02

    Another way to do this would be to respond to the UITableViewDelegate method willDisplayHeaderView. The passed view is actually an instance of a UITableViewHeaderFooterView.

    The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView method.)

    You could then respond to the titleForHeaderInSection method to reuse this configured header with different section titles.

    Objective-C

    - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
        UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    
        header.textLabel.textColor = [UIColor redColor];
        header.textLabel.font = [UIFont boldSystemFontOfSize:18];
        CGRect headerFrame = header.frame;
        header.textLabel.frame = headerFrame;
        header.textLabel.textAlignment = NSTextAlignmentCenter;
    }
    

    Swift 1.2

    (Note: if your view controller is a descendant of a UITableViewController, this would need to be declared as override func.)

    override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
    {
        let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    
        header.textLabel.textColor = UIColor.redColor()
        header.textLabel.font = UIFont.boldSystemFontOfSize(18)
        header.textLabel.frame = header.frame
        header.textLabel.textAlignment = NSTextAlignment.Center
    }
    

    Swift 3.0

    This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:

    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        guard let header = view as? UITableViewHeaderFooterView else { return }
        header.textLabel?.textColor = UIColor.red
        header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        header.textLabel?.frame = header.frame
        header.textLabel?.textAlignment = .center
    }
    

提交回复
热议问题