I have the following setup: A UIView adds a bunch of subviews (UILabels) programmatically, and sets also the autolayout constraints, so that the distance between the labels and between the UIViews edges is 10 each. The goal is that the UIView sets its size accordingly to the content of all the subviews (labels with dynamic text) including the spaces.
I use the following code, but it seems not to work. The UIView doesn't resize, it shrinks the labels.
// setup of labelList somewhere else, containing the label data
var lastItemLabel: UILabel? = nil
var i = 1
for item in itemList {
let theLabel = UILabel()
// ... label setup with text, fontsize and color
myView.addSubview(theLabel)
theLabel.translatesAutoresizingMaskIntoConstraints = false
// If it is the second or more
if let lastLabel = lastItemLabel {
theLabel.leadingAnchor.constraint(equalTo: lastLabel.trailingAnchor, constant: 12).isActive = true
theLabel.topAnchor.constraint(equalTo: myView.topAnchor, constant: 10).isActive = true
// if it is the last label
if i == labelList.count {
theLabel.trailingAnchor.constraint(equalTo: myView.trailingAnchor, constant: 12).isActive = true
}
}
// If it is the first label
else {
theLabel.leadingAnchor.constraint(equalTo: myView.leadingAnchor, constant: 12).isActive = true
theLabel.topAnchor.constraint(equalTo: myView.topAnchor, constant: 10).isActive = true
}
lastItemLabel = theLabel
i += 1
}
myView
to a scroll view? If not, how is it constrained to its superview? – Paulw11myView
inside the storyboard? (Forgive me, @Paulw11 already asked this.) – dfdmyView
is constrained to the scenes root view then it is never going to get any larger. You will need to use a scrollview. – Paulw11