如何通过父视图管理文本标签高度

问题描述 投票:2回答:1

我有一些问题。我试图制作自定义表头部分。这是我的代码:

   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
    }

这是结果:enter image description here

我标记并注意到蓝色和黄色,标签高度与标题视图不同。有人可以帮我管理textlabel高度到标题视图高度,以及如何对齐文本verticaly

ios swift uitableview
1个回答
3
投票

标签高度与标题视图不同

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

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 36.0
}

基于height: 36let sectionHeader = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 36))

如何垂直对齐文本

headerName.textAlignment = .center
© www.soinside.com 2019 - 2024. All rights reserved.