0
votes

I have an UIView in my Storyboard. Leading and Trailing is 16, width of the element is not fixed.

enter image description here

I am appending UILabels to this UIView (-container), which will move to the next "row", when the new and existing UILabel exceeds the width of the container. The "containerWidth" (UIView.frame.size.width) is 382.

**// If current X + label width will be greater than container view width
// .. move to next row**
if (currentOriginX + labelHashtag.frame.width > containerWidth) {
      currentOriginX = 0
      currentOriginY += tagHeight + tagSpacingY
      }

It works fine for iPhone XSM:

enter image description here

But when I run my code on an iPhone 8, the container width is still 382 and the UILabels appearing out of my screen:

enter image description here

Why is the size of my UIView always the same? Why is there no automatically resizing when I use constraints, depending on the device?

1
basically this kind of designs should be handle with UICollectionView. What is your originX? try like GetMaxWidth(labelHashtag) instead of labelHashtag.frame.width - Ram
It could be because the label gets a larger size than expected, as the size is not jet determined before adding to the view. - Thijs van der Heijden

1 Answers

0
votes

Where do you add the labels from? If you add them from viewDidLoad() method, then this is the expected outcome, because your container view will have the exact same width as in the storyboard at that point, then it will be resized with respect to the device screen size. You can use viewDidAppear(_:) method to layout the labels, but you'll have to take care as there could be a small delay from the point of screen appearance and the labels being rendered on the screen.

Do not use viewDidLayoutSubviews() to create and add the labels, because that method will be called multiple times. However, you can use viewDidLayoutSubviews() to recompute the position of the labels (it would be, in fact, the approach I would recommend).

So my recommendation is:

  1. Create the labels in viewDidLoad() method
  2. Take care to have a reference to your labels (an array most probably)
  3. In viewDidLayoutSubviews() compute the positions of the labels.