C. Albert C. Albert - 1 year ago 188
Swift Question

Swift - Changing the vertical alignment of title for Header section in a TableView

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.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?

Answer Source

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"
return headerView
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download