Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TableView Section Change Header Alignment

I have This tableView Here :TableView Section Header Example

With the default left text alignment which i would like to change to a right text alignment . How can i do this ?

EDIT:

Now it looks like this : How It Looks Now

like image 421
Newbie Questions Avatar asked Nov 05 '16 17:11

Newbie Questions


2 Answers

Swift 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
}
like image 58
Ahmadreza Avatar answered Nov 01 '22 17:11

Ahmadreza


You have to do this in UITableView Datasource method 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
}

EDIT: Modified the code above. You can use the section argument to identify the section you want to modify.

like image 8
Geoherna Avatar answered Nov 01 '22 16:11

Geoherna