-2

I am manually creating the greenView in the viewDidload() method below and add it to miidLeView but its coordinates in the resulting screen is wrong? What is the reason for this? Where should add it to middleView? Thanks.

class ViewController: UIViewController {

    @IBOutlet weak var redView: UIView!

    var greenRegion : UIView!
    let greenRegionHeight : CGFloat = 100.0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.



        greenRegion = UIView(frame: CGRect(x: redView.bounds.size.width*1/8,
                                             y: redView.bounds.size.height/2 - greenRegionHeight/2,
                                             width: redView.bounds.size.width*3/4,
                                             height: greenRegionHeight))

        greenRegion.backgroundColor = UIColor.green
        redView.addSubview(greenRegion)
    }

Here is the screen snapshot

Vicky_Vignesh
  • 584
  • 2
  • 14
eral
  • 123
  • 1
  • 16

1 Answers1

0

You just need to put frame set related code into the viewDidLayoutSubviews method then everything worked as per expectation.

override func viewDidLayoutSubviews() {
    greenRegion = UIView(frame: CGRect(x: redView.bounds.size.width*1/8,
                                       y: redView.bounds.size.height/2 - greenRegionHeight/2,
                                       width: redView.bounds.size.width*3/4,
                                       height: greenRegionHeight))

}

Output:

enter image description here

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
  • Yes, it works when you do it in ViewDidAppear(), too but what is wrong. This behavior came with new xcode update. – eral Apr 22 '20 at 12:28
  • There is nothing related to the XCode update. You're trying to add view before all view positioning set in UI. One more thing it is working ViewDidAppear, It is not working in the viewDidLoad method. If you're going with auto-layout then it is also worked in viewDidLoad method too. Hope it will help you. Another solution is the set frame with some delay. You can consider it OS specific issue not XCode specific issue – Hitesh Surani Apr 22 '20 at 12:42