I want to display horizontal UIStackView with 3 labels in it, but I can't see the labels...
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let stackView = UIStackView(arrangedSubviews: [label1,label2,label3])
stackView.distribution = .fill
stackView.axis = .horizontal
stackView.spacing = 8
stackView.alignment = .center
backgroundColor = .black
addSubview(stackView)
stackView.leftAnchor.constraint(equalTo: leftAnchor, constant: 8).isActive = true
stackView.rightAnchor.constraint(equalTo: rightAnchor, constant: 8).isActive = true
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 8).isActive = true
}
I've tried with anchors, but also unsuccessfully. How to do it?
Couple notes...
You should add subviews to the cell's contentView, not to the cell itself.
From the code you've shown, you're not setting stackView.translatesAutoresizingMaskIntoConstraints = false
You should be using leadingAnchor and trailingAnchor rather than left/right
Here is a starter cell that should get you on your way:
class BogdanCell: UITableViewCell {
let label1: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.text = "Label 1"
v.textAlignment = .center
return v
}()
let label2: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.text = "Label 2"
v.textAlignment = .center
return v
}()
let label3: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.text = "Label 3"
v.textAlignment = .center
return v
}()
let theStackView: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .horizontal
v.alignment = .center
v.distribution = .fill
v.spacing = 8
return v
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
backgroundColor = .black
theStackView.addArrangedSubview(label1)
theStackView.addArrangedSubview(label2)
theStackView.addArrangedSubview(label3)
contentView.addSubview(theStackView)
NSLayoutConstraint.activate([
theStackView.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: 0.0),
theStackView.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: 0.0),
theStackView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: 0.0),
theStackView.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: 0.0),
])
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With