簡體   English   中英

獲取當前設備方向

[英]Get the current device orientation

我知道這個問題之前曾被問過,並試圖實施建議的解決方案,但它對我不起作用。 也許我做錯了什么。 你有什么主意嗎?

這是我的代碼:

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

您具有嵌套函數-無法使用。 更改為此:

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的替代。

**對於需要更多幫助的人,請參見下面的建議**此函數將在大小更改之前被調用,但是您將從參數中知道它

雨燕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)")

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM