how to get the size after apply constraints by code

61 views Asked by At

I am actually adding constraints to view


class SecondViewController: UIViewController {


    @IBOutlet weak var containerView: UIView!

    @IBOutlet weak var containerHeigthconstraint: NSLayoutConstraint!


    let myView : UIView = {
       let view = UIView()
        view.backgroundColor = .black
       view.translatesAutoresizingMaskIntoConstraints = false
       return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        containerHeigthconstraint.constant = containerView.frame.width * 9 / 16 + 40
        containerView.backgroundColor = .green

        setupLayout()



    }

    func setupLayout(){
        containerView.addSubview(myView)
        myView.leftAnchor.constraint(equalTo: containerView.leftAnchor,constant: 10).isActive = true
        myView.rightAnchor.constraint(equalTo: containerView.rightAnchor,constant: -10).isActive = true
        myView.topAnchor.constraint(equalTo: containerView.topAnchor,constant: 10).isActive = true
        myView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor,constant: -10).isActive = true
        print(myView.frame)
    }

}

This is the output and as you can see, myView has width and height, but when I print myView.frame I get (0.0, 0.0, 0.0, 0.0), I'd like to know how can i get the real size after apply constraints.

output in simulator

1

There are 1 answers

0
BevTheDev On BEST ANSWER

Constraints are not applied immediately. When you activate a new constraint, it will mark the view as needing an update, but will not actually perform the update until a future UI cycle.

So you have two options. You can call layoutIfNeeded() after activating the constraints to force them to be applied right away, or you can move your print statement to a later method (such as viewDidAppear()) which will trigger after the updates made by viewDidLoad() have completed. Which option you need will depend on what you're wanting to do with the frame.