3

I am using the following code to populate the headers of my function:

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()

}

Now, I would like to be able to change the vertical alignment of the title in the section, like in the following picture:

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

How can I do that?

C. Albert
  • 45
  • 2
  • 6

3 Answers3

8

Unfortunately there is no way to vertically align the text in a UILabel. This SO post goes into more detail.

But you can accomplish a similar affect by adding the label to a parent UIView, and constraining it to the bottom. Then you can return that view in the viewForHeaderInSection tableview Data-source method

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
Community
  • 1
  • 1
Lahav
  • 781
  • 10
  • 22
  • Perfect! I deleted that two functions that I was using, and now I am using just your code inside the function "func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?", as you said. Thank you! – C. Albert Jul 26 '16 at 01:35
  • Great. Glad to help! – Lahav Jul 26 '16 at 01:37
  • This is the best solution, Thank you. One question though, when I scroll on my tableView - the header section doesnt go with the table view, it stays static. do you know why? – Sipho Koza Sep 13 '18 at 11:08
0

I would suggest to add a footer if you want to drop your label a little bit down.

Simran Singh
  • 445
  • 6
  • 8
-1

This code will vertical align the label, not sure its a great approach but sure works. you would rather create a view and use 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
Faraaz
  • 137
  • 1
  • 11