【问题标题】:Swift - Changing the vertical alignment of title for Header section in a TableViewSwift - 在 TableView 中更改标题部分的垂直对齐方式
【发布时间】:2016-07-26 00:41:56
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

    标签: swift uitableview swift2


    【解决方案1】:

    不幸的是,没有办法垂直对齐 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
    

    【讨论】:

    • 完美!我删除了我正在使用的两个函数,现在我只在函数“func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?”中使用你的代码,正如你所说。谢谢!
    • 太棒了。很高兴为您提供帮助!
    • 这是最好的解决方案,谢谢。但是有一个问题,当我在 tableView 上滚动时 - 标题部分不与 table view 一起使用,它保持静态。你知道为什么吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      此代码将垂直对齐标签,不确定它是一种很好的方法,但确实有效。您宁愿创建一个视图并使用 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
      

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 1970-01-01
        • 2013-07-23
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-30
        • 1970-01-01
        相关资源
        最近更新 更多