d0xi45
d0xi45

Reputation: 155

Programmatically adding constraints to a UITableView header

I have a header on my tableview, which has an image and a label. I want to center the UIImage and have the label pinned underneath it. This is my code currently:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerLabel = UILabel()
    let logoView = UIImageView()

    headerLabel.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 21)
    headerLabel.text = self.navigationItem.title
    headerLabel.textColor = UIColor.white
    headerLabel.backgroundColor = UIColor.clear
    headerLabel.textAlignment = NSTextAlignment.center

    logoView.frame = CGRect(x: 0, y: 0, width: 90, height: 90)
    let logo: UIImage = UIImage(named: self.navigationItem.title!)!
    logoView.image = logo
    logoView.contentMode = .scaleAspectFill

    view.addSubview(headerLabel)
    view.addSubview(logoView)

    return topView
}

This puts the label centered on the top of the header, and the logo in the top left corner. How can I add constraints (programmatically, no storyboard) to center the image and pink the label below it? I've been using programmatic constraints quite a bit (i.e. something.leftAnchor.constraint(equalTo....) but I'm not sure how to apply it in this situation as it's my first use of a header.

Upvotes: 0

Views: 2048

Answers (2)

Vileriu
Vileriu

Reputation: 25

You can use that code to set default paddings.

if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0 }

Upvotes: 0

ystack
ystack

Reputation: 1805

I want to center the UIImage and have the label pinned underneath it.

This can be achieved by making the framing logic of each subview dependent of the neighbouring views. Whilst doing this programmatically, one has to be extra careful about the geometric calculations involved.

This snippet should do it:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let logoView = UIImageView()

    logoView.frame = CGRect(x: tableView.center.x - 90/2, y: 0, width: 90, height: 90)
    let logo: UIImage = UIImage(named: self.navigationItem.title!)!
    logoView.image = logo
    logoView.contentMode = .scaleAspectFill

    view.addSubview(logoView)

    let headerLabel = UILabel()
    headerLabel.frame = CGRect(x: 0, y: logoView.frame.size.height, width: view.frame.width, height: 21)
    headerLabel.text = self.navigationItem.title
    headerLabel.textColor = UIColor.white
    headerLabel.backgroundColor = UIColor.clear
    headerLabel.textAlignment = NSTextAlignment.center

    view.addSubview(headerLabel)

    return topView
}

Upvotes: 3

Related Questions