I am trying to experiment with constraints in Swift Playground, and going crazy. I have a small class CLListTableViewCell: UITableViewCell
with a UILabel in it:
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Here is a great text"
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .left // text alignment in center
return label
}()
I have a function to set up the layout, which I call at the end of init:
func addSubViewsAndLayout() {
contentView.addSubview(nameLabel)
let views = ["nameLabel": nameLabel]
let horizontalConstraintsStringRepresentation = "H:|-[nameLabel]-|"
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: horizontalConstraintsStringRepresentation, options: .alignAllCenterY, metrics: nil, views: views)
let verticalConstraintsStringRepresentation = "V:|-[nameLabel]-|"
let verticalNameConstraints = NSLayoutConstraint.constraints(withVisualFormat: verticalConstraintsStringRepresentation, options: .alignAllLeading, metrics: nil, views: views)
NSLayoutConstraint.activate(horizontalConstraints)
NSLayoutConstraint.activate(verticalNameConstraints)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubViewsAndLayout()
}
All I get is a beautiful, white, empty cell. Anybody could point to what I am doing wrong here? Any missing constraint? There is no indication in the Playground console.
--- EDIT ---
The issue seems to be coming from the tableView in which I display the cell. Here is the code:
class TableViewController : UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CLListTableViewCell ?? CLListTableViewCell(style: .default, reuseIdentifier: "cell")
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section)"
}
}
--- EDIT 2 ---
Here is a screenshot of the result.