Incorrect Frame Position when defined in ViewDidLayoutSubviews

830 Views Asked by At

I have an imageView inside an ovalView constrained with auto layout.

Inside viewDidLayoutSubviews(), I am creating a UILabel

let label = UILabel(frame: imageView.frame)
imageView.superview?.addSubview(label)

The frame of label shows slightly off-centered from imageView.

However, if I move my above code inside viewDidAppear(), label is perfectly centered to imageView but user sees the change which is undesireable.

How do I keep my code in viewDidLayoutSubviews() and make it work?

2

There are 2 best solutions below

0
Kashif On BEST ANSWER

For others, who may be facing similar issues. I was able to keep my code in viewDidLayoutSubviews() by adding

self.view.layoutIfNeeded() 

in my code after

let label = UILabel(frame: imageView.frame)
imageView.superview?.addSubview(label)
6
Rashwan L On

When viewDidLayoutSubviews is called you can't assume that your views have their final frames before that method is called. In your case that's what happened. When you call viewDidAppear your view has drawn all its frames and you get the right frame that's why it works for you. So call it in viewDidAppear instead.