0
votes

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
}
1
Are you adding myView to a scroll view? If not, how is it constrained to its superview?Paulw11
myView is UIView in storyboard within the main view (outlet)FrankZp
Then the question to ask is what constraints do you have on myView inside the storyboard? (Forgive me, @Paulw11 already asked this.)dfd
Make sure you call setNeedsLayout when updating your constraints... developer.apple.com/documentation/uikit/uiview/… or layoutIfNeeded developer.apple.com/documentation/uikit/uiview/…user5890979
If myView is constrained to the scenes root view then it is never going to get any larger. You will need to use a scrollview.Paulw11

1 Answers

1
votes

Since you need your content to be larger than the physical display of the device, you will need to add a UIScrollView to contain your labels.