【问题标题】:Get the current device orientation获取当前设备方向
【发布时间】:2017-01-15 09:27:53
【问题描述】:

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

这是我的代码:

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
        }
      }
    }
 }

【问题讨论】:

标签: ios swift uiviewcontroller uidevice


【解决方案1】:

你有嵌套的函数——那是行不通的。改成这样:

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 的覆盖。

【讨论】:

    【解决方案2】:

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

    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)")
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多