I've created a UIView
programmatically using layout anchors
. Now I want to add a UILabel
inside this view. Here is my code so far :
let centerView = UIView()
centerView.translatesAutoresizingMaskIntoConstraints = false
centerView.backgroundColor = UIColor.white
view.addSubview(centerView)
centerView.leftAnchor.constraint(equalTo: view.leftAnchor, constraint: 20).isActive = true
centerView.rightAnchor.constraint(equalTo: view.rightAnchor, constraint: -20).isActive = true
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Testing"
label.textColor = UIColor.black
centerView.addSubview(label)
label.leftAnchor.constraint(equalTo: centerView.leftAnchor).isActive = true
I thought this label would be displayed in reference to centerView
but it is rather being displayed in reference to the UIWindow
. This is the current view hierarchy :
UIWindow --> UIView (centerView) --> UILabel (label)
I need to add multiple labels inside centerView
and as per my understanding, this chain will get longer whereas I want several labels to be all under centerView
UIWindow
|
UIView (centerView)
/ | \
Label 1 Label 2 Label 3
How can I achieve this type of hierarchy?
Auto Layout anchors make it easy to position your views relative to others. There are lots of anchors to choose from: leading and trailing edges, top and bottom edges, center X and center Y, and more. To explore anchors further, try typing child. anchor and exploring the code completion options.
A factory class for creating layout constraint objects using a fluent API.
A layout anchor representing the leading edge of the view's frame.
You're doing it correctly, you just haven't provided enough constraints. I tried your code in a Swift Playground and added a few additional constraints and it shows that the label is placed relative to the centerView
as expected:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 500))
let centerView = UIView()
centerView.translatesAutoresizingMaskIntoConstraints = false
centerView.backgroundColor = UIColor.white
view.addSubview(centerView)
centerView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
centerView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
centerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
centerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Testing"
label.textColor = UIColor.black
label.backgroundColor = UIColor.yellow
centerView.addSubview(label)
label.leftAnchor.constraint(equalTo: centerView.leftAnchor).isActive = true
label.topAnchor.constraint(equalTo: centerView.topAnchor).isActive = true
view.layoutIfNeeded()
Here is is running in a Playground:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With