Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Frame and bounds not being updated while setting constraints

While creating constraints, it seems like the frame and bounds of a constrained UI element is not being updated immediately.

NSLayoutConstraint.activate([
            counterLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            counterLabel.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: view.frame.size.height/100),
            counterLabel.widthAnchor.constraint(equalToConstant: view.frame.size.width/1.2),

            gameButton.heightAnchor.constraint(equalToConstant: (view.bounds.size.height-counterLabel.frame.maxY)) // THIS DOES NOT WORK

It turns out that despite creating the constraints for counterLabel, its frame and bounds are still (0,0,0,0). The solution that I found to work was putting the gameButton’s height anchor within viewDidLayoutSubviews.

Why is this the case? I tried looking for other threads and documentation about this, but couldn’t find much.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

write layoutIfNeeded() before using frame or bounds
for example

layoutIfNeeded()
myView.layer.cornerRadius = myView.frame.width / 2 

now frame and bounds returns true values

in your case, maybe you need to set constraints, then calculate them and store your constraints in variables.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading