在Swift中获取设备方向

时间:2014-09-11 20:40:35

标签: ios swift orientation

我想知道如何在Swift中获取当前的设备方向?我知道有一些Objective-C的例子,但我还没有能够在Swift中使用它。

我正在尝试获取设备方向并将其放入if语句中。

这是我遇到的问题最多的一行:

[[UIApplication sharedApplication] statusBarOrientation]

17 个答案:

答案 0 :(得分:59)

你可以使用:

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
    var text=""
    switch UIDevice.currentDevice().orientation{
    case .Portrait:
        text="Portrait"
    case .PortraitUpsideDown:
        text="PortraitUpsideDown"
    case .LandscapeLeft:
        text="LandscapeLeft"
    case .LandscapeRight:
        text="LandscapeRight"
    default:
        text="Another"
    }
    NSLog("You have moved: \(text)")        
}

SWIFT 3更新

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
    var text=""
    switch UIDevice.current.orientation{
    case .portrait:
        text="Portrait"
    case .portraitUpsideDown:
        text="PortraitUpsideDown"
    case .landscapeLeft:
        text="LandscapeLeft"
    case .landscapeRight:
        text="LandscapeRight"
    default:
        text="Another"
    }
    NSLog("You have moved: \(text)")        
}

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}

通知您可以查看:IOS8 Swift: How to detect orientation change?

  

注意: didRotateFromInterfaceOrientation 已弃用   适用于iOS 2.0及更高版本的 viewWillTransitionToSize

答案 1 :(得分:47)

要获得状态栏(及其UI)方向,例如您拥有的Objective-C代码,它只是:

UIApplication.sharedApplication().statusBarOrientation

您还可以使用UIDevice的orientation property

UIDevice.currentDevice().orientation

但是,这可能与您的用户界面的方向不符。来自文档:

  

属性的值是一个表示当前值的常量   设备的方向。该值代表物理   设备的方向可能与当前不同   应用程序用户界面的方向。看到   “UIDeviceOrientation”用于描述可能的值。

答案 2 :(得分:23)

Apple最近摆脱了Landscape vs. Portrait的想法,并且更喜欢我们使用屏幕尺寸。但是,这有效:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.currentDevice().orientation.isLandscape.boolValue {
        print("landscape")
    } else {
        print("portrait")
    }
}

答案 3 :(得分:17)

struct DeviceInfo {
struct Orientation {
    // indicate current device is in the LandScape orientation
    static var isLandscape: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isLandscape
                : UIApplication.shared.statusBarOrientation.isLandscape
        }
    }
    // indicate current device is in the Portrait orientation
    static var isPortrait: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isPortrait
                : UIApplication.shared.statusBarOrientation.isPortrait
        }
    }
}}

swift4回答: 我就是这样做的,

1.适用于各种视图控制器的工作

2.当用户旋转应用程序时也可以工作

3.也是第一次安装应用程序

答案 4 :(得分:12)

要查找当前的设备方向,只需使用以下代码:

  

UIApplication.sharedApplication()。statusBarOrientation

for swift 3.0

  

UIApplication.shared.statusBarOrientation

答案 5 :(得分:12)

Swift 4:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            print("landscape")
        } else {
            print("portrait")
        }
    }

答案 6 :(得分:8)

我在使用InterfaceOrientation方面遇到了问题,但除了在加载时没有访问方向外,它工作正常。所以我尝试了这个,它是一个守门员。这是有效的,因为bounds.width总是引用当前方向而不是绝对的nativeBounds.width

    if UIScreen.mainScreen().bounds.height > UIScreen.mainScreen().bounds.width {
        // do your portrait stuff
    } else {    // in landscape
        // do your landscape stuff
    }

我从willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval)viewDidLoad拨打此电话,但它很灵活。

感谢zSprawl指向该方向的指针。我应该指出,这只适用于iOS 8及更高版本。

答案 7 :(得分:8)

因此,如果Apple贬低整个方向字符串(“肖像”,“横向”),那么您所关心的只是宽度与高度的比率。 (有点像@bpedit的答案)

当您将宽度除以高度时,如果结果小于1,则主屏幕或容器或其他任何处于“纵向”“模式”。如果结果大于1,那就是“风景”画。 ;)

{{1}}

(我猜测如果你使用这种方法,那么当比率恰好为1,宽度和高度相等时,你可能并不真正关心具体处理条件。)

答案 8 :(得分:4)

快速3 +

基本上:

NotificationCenter.default.addObserver(self, selector: #selector(self.didOrientationChange(_:)), name: .UIDeviceOrientationDidChange, object: nil)

@objc func didOrientationChange(_ notification: Notification) {
    //const_pickerBottom.constant = 394
    print("other")
    switch UIDevice.current.orientation {
        case .landscapeLeft, .landscapeRight:
            print("landscape")
        case .portrait, .portraitUpsideDown:
            print("portrait")
        default:
            print("other")
    }
}

:)

答案 9 :(得分:2)

Swift 3 ,基于Rob的回答

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if (size.width / size.height > 1) {
        print("landscape")
    } else {
        print("portrait")
    }
}

答案 10 :(得分:2)

   override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    if (toInterfaceOrientation.isLandscape) {
        NSLog("Landscape");
    }
    else {
        NSLog("Portrait");
    }
}

答案 11 :(得分:2)

statusBarOrientation 已被弃用,因此不再不再可用可以像 在以上答案

在此代码中可以定位,而无需担心折旧。 雨燕5 ioS 13.2 已测试100%

struct Orientation {
    // indicate current device is in the LandScape orientation
    static var isLandscape: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isLandscape
                : (UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape)!
        }
    }
    // indicate current device is in the Portrait orientation
    static var isPortrait: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isPortrait
                : (UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isPortrait)!
        }
    }
}

答案 12 :(得分:1)

我发现Swift中的Obj-C代码的替代代码

if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) 

if UIApplication.shared.statusBarOrientation.isLandscape

注意:我们正在尝试查找状态栏方向是否为横向。如果它是横向的,则if语句为true。

答案 13 :(得分:1)

Swift 5

适用于 SwiftUI 和基于故事板的应用程序。此外,检查轮换和特征处理程序

lowres_file = str(lowres_file)

with open(lowres_file, 'r') as f_in:
    with open(lowres_file_converted, 'w') as f_out:
        for line in f_in:
            print(line)
            if line[0] != ' ':
                f_out.write(line)
            else:
                split_line = np.array(line[1:-1].split(' '), dtype = int)
                split_line[split_line == 106] = -9999
                split_line[split_line == 1] = 0.1
                split_line = np.array(split_line, dtype = str)
                new_line = ' ' + ' '.join(split_line) + '\n'
                f_out.write(new_line)

答案 14 :(得分:0)

尝试使用 horizontalSizeClassverticalSizeClass

import SwiftUI

struct DemoView: View {
    
    @Environment(\.horizontalSizeClass) var hSizeClass
    @Environment(\.verticalSizeClass) var vSizeClass
    
    var body: some View {
        VStack {
            if hSizeClass == .compact && vSizeClass == .regular {
                VStack {
                    Text("Vertical View")
                }
            } else {
                HStack {
                    Text("Horizontal View")
                }
            }
        }
    }
}

在此 tutorial 中找到它。相关 Apple 的 documentation

答案 15 :(得分:0)

对于任何看到过 iOS 13 的人:

对我来说最可靠的方法现在已被弃用,尽管它(仍在)工作:

print(UIApplication.shared.statusBarOrientation.isPortrait)

现在应该走的路是什么:

if UIApplication.shared.windows.first?.
windowScene?.interfaceOrientation.isPortrait ?? true {
    print("Portrait")
} else {
    print("Landscape")
}

答案 16 :(得分:0)

Swift 5 – 解决方案:在应用启动时和设备旋转期间检查方向:

// app start
override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let orientation = self.view.window?.windowScene?.interfaceOrientation {
        let landscape = orientation == .landscapeLeft || orientation == .landscapeRight
    }
}

// on rotation
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    let landscape = UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight
}