Adding a label to table view header

Hello everyone - my first post…
I’ve worked through Brian Moakley’s excellent “Beginning Table Views” video tutorial and now want to add a label to the header. I can do this by doing this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UITableViewHeaderFooterView()
let frame = tableView.frame
let label = UILabel(frame: CGRect(x: tableView.frame.width/2, y: 5, width: tableView.frame.width/5, height: 20))
header.addSubview(label)
label.backgroundColor = UIColor.blue
header.addSubview(label)
return header
}

However, I’ve had to define the size of the label in relation to the tableView width and then use fixed top and height values. I really want to do the size in relation to the header (UITableViewHeeaderFooterView()), but these are not available in this function.
I realise I can set the height of the header, but prefer to use .automaticDimension.
So, my question is, is it possible to align the label in the header with margins that I define?
Hope that’s clear,
Thanks, johno

Hello again,
If anyone is interested, I’ve solved my question! Here it is.
This adds a right justified label with the text “Hi” to the header. Note that the issue with setting the constraint priorities is related to what appear to be spurious run-time warnings about auto layout - discussed here:

This is the code I’ve implemented and it seems to work fine. The main thing to watch will be deciding how wide to make the label

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UITableViewHeaderFooterView()
let marginGuide = header.contentView.layoutMarginsGuide
let label = UILabel()
label.text = “Hi”
label.translatesAutoresizingMaskIntoConstraints = false
header.contentView.addSubview(label)
var constraint = label.widthAnchor.constraint(equalToConstant: 20)
constraint.priority = UILayoutPriority(999)
constraint.isActive = true
constraint = label.topAnchor.constraint(equalTo: marginGuide.topAnchor)
constraint.priority = UILayoutPriority(999)
constraint.isActive = true
constraint = label.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor)
constraint.priority = UILayoutPriority(999)
constraint.isActive = true
constraint = label.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor)
constraint.priority = UILayoutPriority(999)
constraint.isActive = true
return header
}

Johno

Hi @johno and welcome to the community! That’s awesome that you were able to figure it out. Thanks for the update.

Best,
Gina

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.