Search code examples
iosuitextfieldswift4nslayoutconstraintcgrect

how to combine NSLayout Constraints with CGrect frame (Swift4)


I am trying to create a textfield pragmatically, using no storyboard. My current code is having a compile error. I need to use NSLayout constraint to make sure my code can work on both a ipad and iphone.

    import UIKit
var aa:[NSLayoutConstraint] = []
class ViewController: UIViewController {

var btn : UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    btn = UITextField(frame: CGRect(x: 50, y: 100, width: 200, height: 50))

    let leadingc2 = btn.widthAnchor.constraint(equalToConstant: 80)
    let trailingC2 = btn.heightAnchor.constraint(equalToConstant: 50)
    let topc2 = btn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -50)
    let bottomc2 = btn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -250)

    aa = [leadingc2,trailingC2,topc2,bottomc2]

    NSLayoutConstraint.activate(aa)
    self.view.addSubview(btn)
}


}

Solution

  • Could you try rewriting these two lines in this order:

    view.addSubview(btn)
    NSLayoutConstraint.activate(aa)
    

    Constraints may not be applied to views that don't share a hierarchy, which means you cannot activate the constraints between the button and its superview until the button is added to that superview.