Search code examples
iosswift4nslayoutconstraintsubview

nslayout constraint not making object appear


My code below is using code no storyboard to display a object. The project builds but I can not see the textfield I am trying to programmatically place. I dont know why the code is not appearing. I am trying to not use the storyboard.

 var enterWeight = UITextField()




override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(enterWeight)

    enterWeight.backgroundColor = UIColor.blue


    NSLayoutConstraint.activate ([

        enterWeight.topAnchor.constraint(equalTo: view.topAnchor, constant : 20),
        enterWeight.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant : 20),
        enterWeight.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 20),
        enterWeight.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : 20),


        enterWeight.widthAnchor.constraint(equalToConstant: 50),
        enterWeight.heightAnchor.constraint(equalToConstant: 30)

        ])

}

Solution

  • You have conflicting constraints and they will never work this way.

    First, as mentioned by iFlames, you need to set translatesAutoresizingMaskIntoConstraints to false:

    enterWeight.translatesAutoresizingMaskIntoConstraints = false
    

    Then:

    NSLayoutConstraint.activate ([
            enterWeight.topAnchor.constraint(equalTo: view.topAnchor, constant : 20),
            enterWeight.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 20),
            enterWeight.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : 20),
            enterWeight.heightAnchor.constraint(equalToConstant: 30)
    ])
    

    By giving the textField a leading and trailing you already gave it a width constraint implicitly, it's the width of view minus the constants (20 * 2), so you shouldn't give it a width constraint, it will cause a conflict.