获取当前的设备方向

时间:2017-01-15 09:27:54

标签: ios swift uiviewcontroller uidevice

我知道之前曾问过这个问题,并尝试实施建议的解决方案,但它对我没有用。也许我做错了。你有什么想法吗?

这是我的代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var test: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    test.backgroundColor = UIColor.darkGray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // No need for semicolon

    func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            test.backgroundColor = UIColor.purple
        } else {
            test.backgroundColor = UIColor.blue
        }
      }
    }
 }

2 个答案:

答案 0 :(得分:3)

你有嵌套功能 - 不会起作用。将其更改为:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // No need for semicolon
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        test.backgroundColor = UIColor.purple
    } else {
        test.backgroundColor = UIColor.blue
    }
}

事实上,您可以使用您已经显示的代码摆脱viewWillLayoutSubviews的覆盖。

答案 1 :(得分:1)

**对于那些需要额外帮助的人,请参阅以下建议 **此函数将在更改大小之前调用,但您将从参数

中了解它

Swift 3.x +

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        //Landscape

            print("before transition")
            print("w "+"\(width)")
            print("h "+"\(height)")
            print("to size")
            print("w "+"\(size.width)")
            print("h "+"\(size.height)")

    } else {
        //Portrait      

            print("before transition")
            print("w "+"\(width)")
            print("h "+"\(height)")
            print("to size")
            print("w "+"\(size.width)")
            print("h "+"\(size.height)")

    }

}
相关问题