ChildViewController.view.frame changes during screen rotation

Asked 2 years ago, Updated 2 years ago, 36 views

class ViewController:UIViewController {

letchildViewController: UIViewController= UIViewController()

override func viewDidLoad(){
    super.viewDidLoad()

    childViewController.view.backgroundColor=UIColor.greenColor()
    self.addChildViewController (childViewController)
    childViewController.didMoveToParentViewController(self)
    self.view.addSubview(childViewController.view)
    childViewController.view.frame = CGRect (x:0, y:0, width:300, height:300)

    self.addObserver(self, forKeyPath: "childViewController.view.frame", options: .New, context:nil)
}

override func viewWillTransitionToSize (size: CGSize, with TransitionCoordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator:coordinator)
    childViewController.view.frame = CGRect (x:0, y:0, width:300, height:300)
}

override funcoveValueForKeyPath(keyPath:String?, ofObject object:AnyObject?,change:[String:AnyObject]?,context:UnsafeMutablePointer<Void>){
    print("\(childViewController.view.frame)")
}
}

If you execute the above code, you will see

when the screen rotates.
 (0.0, 0.0, 300.0, 300.0)
(0.0, 0.0, 0.0, 622.0)

appears.

childViewController.view.frame = CGRect (x:0, y:0, width:300, height:300)

After execution, the frame is forced to be rewritten, but could you tell me how to prevent it from being rewritten to (0,0,0,622)?

Thank you for your cooperation.

ios swift xcode

2022-09-30 15:03

1 Answers

Resize view

instead of
Place a 300x300 UIView in the view
I think it's better.


2022-09-30 15:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.