Ios 如何按父视图管理文本标签高度

Ios 如何按父视图管理文本标签高度,ios,swift,uitableview,Ios,Swift,Uitableview,我有些问题。我尝试创建自定义表格标题部分。这是我的密码: func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionHeader = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 36)) sectio

我有些问题。我尝试创建自定义表格标题部分。这是我的密码:

   func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionHeader = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 36))

        sectionHeader.backgroundColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1)

        tableView.backgroundColor = colors.background

        let headerName = UILabel(frame: CGRect(x: 15, y: 0, width: tableView.frame.size.width, height: sectionHeader.frame.size.height))

        headerName.font = UIFont(name: "Helvetica", size: 12)
        headerName.text = sectionHeaders[section]
        headerName.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
        headerName.clipsToBounds = true

        sectionHeader.addSubview(headerName)

        return sectionHeader
    }
结果如下:

我用蓝色和黄色标记并注意到,标签的高度与headerview不一样。有人能帮助我如何管理文本标签高度到标题视图高度,以及如何对齐文本垂直方向吗

标签高度与headerview不同

首先,您应该设置节标题的高度:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 36.0
}
基于
height:36
from
let sectionHeader=ui视图(帧:CGRect(x:0,y:0,宽度:tableView.frame.size.width,height:36))

如何垂直对齐文本


您是否使用过
func tableView(u tableView:UITableView,heightForHeaderInSection:Int)
headerName.textAlignment = .center