以下のコードは、画面を回転させても、常に画面の中央付近に青い四角が表示されることを目的にして書いたものですが、Simulatorで実行してみると、起動直後はそうなっても、一度回転させると、四角は中央に表示されません。どうも回転させる前の画面の幅や高さをそのまま覚えているような気配です。どうしたら、回転後の画面の幅や高さを呼び出せるのか教えて頂ければ幸いです。よろしくお願いします。
(Device Orientationは、Portrait, Upside Down, Landscape Left/Right全てオンにしています。また、Universal(iPhone, iPad両対応)にしています。)
import UIKit
class ViewController: UIViewController {
var box: UILabel! var sW = UIScreen.mainScreen().bounds.size.width var sH = UIScreen.mainScreen().bounds.size.height override func viewDidLoad() { super.viewDidLoad() boxCreate() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { box.removeFromSuperview() boxCreate() } func boxCreate () { sW = UIScreen.mainScreen().bounds.size.width sH = UIScreen.mainScreen().bounds.size.height box = UILabel(frame: CGRect(x: sW / 4, y: sH / 4, width: sW / 2, height: sH / 2)) box.backgroundColor = UIColor.blueColor() view.addSubview(box) } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .All } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }
}
回答1件
あなたの回答
tips
プレビュー