Search code examples
swiftviewdidappearviewdidlayoutsubviews

Incorrect Frame Position when defined in ViewDidLayoutSubviews


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?


Solution

  • 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)