Basic Constraints

Hello everyone, My problem is very basic so I think pretty much everyone can help me with that.
My problem is that I want to set my label constraints programmatically in the way so it depends on view (self) constraints. like width of the label and height . I want to set width equal to :

let tempLabelSideSize = self.frame.size.width / 3
widthAnchor.constraint(equalToConstant: tempLabelSideSize).isActive = true

but when running the project I see that in the moment when setting the constraint , the frame.size is 0,0 so is the bounds.

I believe that it happens because at the moment when Xcode is setting my constraints the view doesn't have size yet. so it sets to zero only after view is ready it gives size to view itself
but I still don't know how to set constraints this way.
I want my constraints to be depending on the view. don't want to hard code it cause on other devices it could break UI pretty hard.
Thank you in advance <3

I think this question is best suited for Apple developer forums.

1 Like

You may be able to use an AspectRatio Constraint https://stackoverflow.com/questions/31334017/how-can-i-set-aspect-ratio-constraints-programmatically-in-ios

I had similar problem, but all the lables and elements I add to container or stackView for automatic resizing. Maybe that way no need to specify : self.frame.size.width / 3 that can be tricky to debug.
tempLabelSideSize.translatesAutoresizingMaskIntoConstraints = false

let container = self.contentView
container.addSubview(tempLabelSideSize) /// or similar

tempLabelSideSize.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: UIEdgeInsets(top: 0, left: 5, bottom: 3, right: 3).left).isActive = true