TableView部分更改标题对齐

New*_*ons 4 text alignment tableview swift

我有这个tableView:TableView节标题示例

使用默认的左侧文本对齐方式,我想将其更改为右侧文本对齐方式.我怎样才能做到这一点 ?

编辑:

现在它看起来像这样: 它看起来如何

Alf*_*lfi 19

斯威夫特4

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Your Header Name"
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.textLabel?.font = UIFont(name: "YourFontname", size: 14.0)
    header.textLabel?.textAlignment = NSTextAlignment.right
}
Run Code Online (Sandbox Code Playgroud)


Geo*_*rna 6

您必须在UITableView Datasource方法中执行此操作 viewForHeaderInSection:

Swift 2.3:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerText = UILabel()
    headerText.textColor = UIColor.lightGrayColor()
    headerText.adjustsFontSizeToFitWidth = true
    switch section{
    case 0:
        headerText.textAlignment = .Center
        headerText.text = "This Header Will Be Centered"
    case 1:
        headerText.textAlignment = .Right
        headerText.text = "This Header Will Be Aligned Right"
    default:
        headerText.textAlignment = .Left
        headerText.text = "Default Will Be Left"
    }

    return headerText
}
Run Code Online (Sandbox Code Playgroud)

编辑:修改了上面的代码。您可以使用该section参数来标识要修改的部分。