This question is being updated every time I act on someone’s suggestion here. Unfortunately though, non of the minor housekeeping suggestions helped enough, so the problem remains.
In the nutshell:
- I have a viewController (secondVC) with a tableView in it (secondTableView).
- Within that tableview, at the very top, I am trying to have a tableHeaderView (with orange background as shown on the attached image).
- Inside of the tableHeaderView I am trying to nest two labels one on top of the other (labelOne on top of labelTwo).
- labelOne is static. I just says "LIST" and remains perpetually unchanged.
- labelTwo is dynamic. It is going to change. It is going to occupy as many lines as needed and the tableHeaderView height should adjust to accommodate and contain both labelOne (LIST) and whatever ends up in labelTwo (long text)
Right now though, as you can see from the picture, labelOne disappeared altogether and labelTwo has weird layout. Something is wrong with constraints I guess. Please help me fix the constraints right.
import UIKit
class SecondVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var secondTableView: UITableView!
var stuff = [("Some other stuff 1"),("Some other stuff 2"),("Some other stuff 3")]
var insertionText: String = ""
override func viewDidLoad() {
super.viewDidLoad()
secondTableView.delegate = self
secondTableView.dataSource = self
let tableHeader = UIView()
secondTableView.tableHeaderView = tableHeader
tableHeader.backgroundColor = .systemOrange
tableHeader.translatesAutoresizingMaskIntoConstraints = false
let size = tableHeader.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let height = size.height
let width = size.width
tableHeader.frame = CGRectMake(0, 0, width, height)
let labelOne = UILabel(frame: tableHeader.bounds)
labelOne.text = "USER:"
labelOne.numberOfLines = 0
labelOne.lineBreakMode = .byWordWrapping
labelOne.textAlignment = .center
labelOne.translatesAutoresizingMaskIntoConstraints = false
let labelTwo = UILabel(frame: tableHeader.bounds)
labelTwo.translatesAutoresizingMaskIntoConstraints = false
labelTwo.text = "Inherited text here: (insertionText)"
labelTwo.numberOfLines = 0
labelTwo.lineBreakMode = .byWordWrapping
labelTwo.textAlignment = .center
labelTwo.translatesAutoresizingMaskIntoConstraints = false
tableHeader.addSubview(labelOne)
tableHeader.addSubview(labelTwo)
labelOne.topAnchor.constraint(
equalTo: tableHeader.layoutMarginsGuide.topAnchor,
constant: 11).isActive = true
labelOne.leadingAnchor.constraint(
equalTo: tableHeader.layoutMarginsGuide.leadingAnchor,
constant: 20).isActive = true
labelOne.trailingAnchor.constraint(
equalTo: tableHeader.layoutMarginsGuide.trailingAnchor,
constant: -20).isActive = true
labelTwo.topAnchor.constraint(
equalTo: labelOne.layoutMarginsGuide.bottomAnchor,
constant: 0).isActive = true
labelTwo.leadingAnchor.constraint(
equalTo: tableHeader.leadingAnchor,
constant: 20).isActive = true
labelTwo.trailingAnchor.constraint(
equalTo: tableHeader.trailingAnchor,
constant: -20).isActive = true
labelTwo.bottomAnchor.constraint(
equalTo: tableHeader.bottomAnchor,
constant: -11).isActive = true }
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let tableHeader = secondTableView.tableHeaderView {
let height = tableHeader.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var headerFrame = tableHeader.frame
if height != headerFrame.size.height {
headerFrame.size.height = height
tableHeader.frame = headerFrame
secondTableView.tableHeaderView = tableHeader } } }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
stuff.count }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = secondTableView.dequeueReusableCell(withIdentifier: "SecondTVCell", for: indexPath) as! SecondTVCell
cell.someOtherStuffLabel.text = stuff[indexPath.row]
return cell } }
2
Answers
You have a mistakes in order when you add views. When you try to configure view size with autolayout you need to set
before adding a view to a superview by:
In your code swift automatically create set of constraints related to labels zero size when you do addSubview(…). After that you add additional constraints that conflict with autogenereted. This is the reason why swift can’t resolve correct size of your view. More about how this property work you can found here: translatesAutoresizingMaskIntoConstraints
Another problem here:
The reason is very same. You try to get size of header from autolayout system before you finish header configuration inside. And bind this size by translatesAutoresizingMaskIntoConstraints property.
So you need to add labels to header view and resolve the first problem with setting translatesAutoresizingMaskIntoConstraints at correct place. Already after this resolve header size and set it into table.
You’re not that far off… but couple of things:
The
.tableHeaderView
needs.translatesAutoresizingMaskIntoConstraints
to be True, not FalseBecause you are using a multi-line label, we have to tell auto-layout how wide the view can be when requesting its "fitting" size – so
viewDidLayoutSubviews()
becomes:Here’s your controller class, with those slight modifications:
I find it very helpful during development to give UI elements contrasting background colors… makes it easy to see the framing at run-time. So I set the header view labels to cyan and yellow, and this is the result:
and when the device is rotated:
Note: when you run this, you will see some auto-layout complaints. That’s because we’re setting constraints on the labels and adding them (and the header view) to the view hierarchy in
viewDidLoad()
… but the constraints have conflicts at that point.We can safely ignore those, but if we want to avoid them we can give the bottom constraint from the second label a priority of less-than required: