Tableview header 标签居中对齐

Tableview header label alignment on center

标签标题对齐方式偏左,但我希望居中。 我的约束有什么问题?

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    var title: UILabel = UILabel()

    title.text = sectionsArray[section]
    title.textColor = UIColor(red: 77.0/255.0, green: 98.0/255.0, blue: 130.0/255.0, alpha: 1.0)
    title.backgroundColor = UIColor(red: 225.0/255.0, green: 243.0/255.0, blue: 251.0/255.0, alpha: 1.0)
    title.font = UIFont.boldSystemFontOfSize(10)

    var constraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[label]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["label": title])

    title.addConstraints(constraint)

    return title
}

我认为您可能需要设置 UILabel 的 textAlignment 属性。即使它居中,我认为文本默认为左对齐。

title.textAlignment = NSTextAlignment.Center

Swift 4中心已重命名为小写。

title.textAlignment = NSTextAlignment.center