iosswiftconstraintslayout-anchor

Creating subviews using layout anchors programmatically


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?


Solution

  • 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:

    Showing the code running the a Playground