Swift - 更改TableView中标题部分的标题的垂直对齐方式

时间:2016-07-26 00:41:56

标签: swift uitableview swift2

我使用以下代码填充函数的标题:

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    switch section {

    case 0: "SECTION 0"

    case 1: "SECTION 1"

    default: break

    }

    return nil
}

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
    var title = UILabel()
    title.font = UIFont(name: "HelveticaNeue-Light", size: 12)!
    title.textColor = UIColor.blackColor()

    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.font=title.font
    header.textLabel?.textColor=title.textColor
    header.backgroundView?.backgroundColor = UIColor.whiteColor()

}

现在,我希望能够更改该部分中标题的垂直对齐方式,如下图所示:

Changing the vertical alignment of the title in the section of the TableView

我该怎么做?

3 个答案:

答案 0 :(得分:6)

不幸的是,没有办法在UILabel中垂直对齐文本。 This SO帖子详细介绍。

但是您可以通过将标签添加到父UIView并将其约束到底部来实现类似的效果。然后,您可以在viewForHeaderInSection tableview数据源方法

中返回该视图
let headerView = UILabel(frame: CGRect(origin: CGPointZero, size: CGSize(width: self.view.frame.width, height: 50)))
let label = UILabel(frame: CGRect(x: 0, y: 20, width: self.view.frame.width, height: 30))
label.text = "Some Text"
headerView.addSubview(label)
return headerView

答案 1 :(得分:0)

此代码将使标签垂直对齐,不确定采用哪种方法很好,但是可以肯定。您宁愿创建一个视图并使用viewForHeaderSection。

guard let header = view as? UITableViewHeaderFooterView else { return }
header.translatesAutoresizingMaskIntoConstraints = false
header.textLabel?.translatesAutoresizingMaskIntoConstraints = false
header.textLabel?.centerYAnchor.constraint(equalTo: header.contentView.centerYAnchor).isActive = true

答案 2 :(得分:0)

如果您想稍微降低标签,我建议添加页脚。