2
class ViewController: UIViewController {

let childViewController: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, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    childViewController.view.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
}

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

上記のコードを実行すると、画面回転時に

(0.0, 0.0, 300.0, 300.0)
(0.0, 0.0, 0.0, 622.0)

と出力されます。

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

実行後、強制的にframeが書き換えられてしまうのですが、(0, 0, 0, 622)に書き換えられないようにする為の方法をご教示頂けませんでしょうか。

よろしくお願い致します。

2
  • 狙いとしては、端末を回転させてもchildViewControllerのviewのサイズを保ちたいということでしょうか?(常にwidthとheight共に300.0に保ちたいということでしょうか?)
    – Takahiro
    2015年11月16日 11:02
  • ご返信ありがとうございます。 狙いにつきましてですが、「(0.0, 0.0, 0.0, 622.0)に書き換えられる理由を知りたい事と、その処理を止める方法」となります。 autoLayoutを使う事で画面回転時にも問題なくframeを設定するといった事はできたのですが、上記の単純なコードでなぜframeの書き換えが起きるのかが気になってしまい、質問として挙げさせて頂きました。
    – Melodybox
    2015年11月16日 16:04

1 件の回答 1

0

viewのサイズを変更する
ではなく、
viewの中に300x300のUIViewを配置する
ほうがいいと思います。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。