I got a
ViewController with a bunch of
Labels ordered in 2 columns (title and description values). All the
Labels are children of the main
I want the right column with the description Labels aligned vertically:
My first attempt:
I set a fixed width constraint
width = 180 to each
Label of the left column. Then each
Label of the right column had a constraint to the corresponding
Label to its left.
This worked and looked fine, but I got this warning I wanted to get rid of:
Fixed width constraints may cause clipping
My second attempt:
Deleted all fixed width constraints of the left side
Labels to get rid of the warning. Right side wasn't aligned anymore.
viewDidLoad() I tried setting all left side
Labels' frame sizes to the size of the longest
Label (in my case "Some long long text")
shorterTitle.frame.size = longTitle.frame.size tinyTitle.frame.size = longTitle.frame.size
This didn't have any visible impact though (left constraints of the right Labels don't seem to be dynamic).
My third attempt:
I ignored the different sizes of the left side
Labels but looked at those on the right.
I check the x position the right side
Label of the longest left side
Label and set this position to all other right side
secondDes.frame.origin.x = firstDes.frame.origin.x thirdDes.frame.origin.x = firstDes.frame.origin.x
This worked out fine but there's a problem to it:
This doesn't work if the value
Labels are empty. In my app these are empty first and then the information of the right side
Labels gets downloaded from a webserver.
So if I do this:
secondDes.frame.origin.x = firstDes.frame.origin.x thirdDes.frame.origin.x = firstDes.frame.origin.x firstDes.text = "test1" secondDes.text = "test2" thirdDes.text = "test3"
the right side won't be aligned correctly.
So I changed the order so the text gets set first and therefore the
Labels get a new width size depending on their new text.
firstDes.text = "test1" secondDes.text = "test2" thirdDes.text = "test3" secondDes.frame.origin.x = firstDes.frame.origin.x thirdDes.frame.origin.x = firstDes.frame.origin.x
Surprisingly this doesn't work neither.
The reason is: The text attributes are set but by the time the last 2 lines are executed the sizes of the
Labels haven't adjusted yet.
So I would have to wait a little bit for the sizes to be applied and then call the last two lines again.
If I did that the user would be able to see the text jump though.
Hope you guys have an idea.