如何在iOS设备上检测方向?

72

我想了解如何在iOS上检测设备的方向。我不需要接收更改通知,只需要当前的方向。这似乎是一个相当简单的问题,但我还没有能够理解它。以下是我迄今为止所做的:

UIDevice *myDevice = [UIDevice currentDevice] ;
[myDevice beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation deviceOrientation = myDevice.orientation;
BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation);
[myDevice endGeneratingDeviceOrientationNotifications];
在我看来这应该可以工作。我启用了设备接收设备方向通知,然后询问它所处的方向,但它没有工作,我不知道原因。
在我的想法里这应该有效。我将设备设置为接收设备方向通知,然后查询它的方向,但结果却不起作用,我不知道原因。

这会有所帮助:http://jayprakashdubey.blogspot.in/2014/07/check-device-orientation.html - Jayprakash Dubey
可能是重复的问题:如何以编程方式确定iPhone界面方向? - Suhaib
13个回答

0

我目前的做法:

+ (BOOL)isPortrait {
    let window = UIApplication.sharedApplication.delegate.window;
    if(window.rootViewController) {
        let orientation =
        window.rootViewController.interfaceOrientation;
        return UIInterfaceOrientationIsPortrait(orientation);
    } else {
        let orientation =
        UIApplication.sharedApplication.statusBarOrientation;
        return UIInterfaceOrientationIsPortrait(orientation);
    }
}

如果由于某种原因没有rootViewController,则应该安全地返回statusBarOrientation...

0

在 Swift 中最可靠的方式是:

public extension UIScreen {

    public class var isPortrait: Bool {
        UIApplication.shared.delegate?.window??.rootViewController?.interfaceOrientation.isPortrait ??
                UIApplication.shared.statusBarOrientation.isPortrait
    }

    public class var isLandscape: Bool { !isPortrait }
}

0
这是我的使用Combine的解决方案,它非常容易与SwiftUI或常规Swift对象一起使用。对于这种真正全局对象,单例对象(静态实例)比“环境”更好。
// Singleton object to keep the interface orientation (and any other global state)
class SceneContext: ObservableObject {
    @Published var interfaceOrientation = UIInterfaceOrientation.portrait
    static let shared = SceneContext()
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    ...
    func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
        SceneContext.shared.interfaceOrientation = windowScene.interfaceOrientation
    }
}

    // if you want to execute some code whenever the orientation changes in SwiftUI
    someView {
        ....
    }
    .onReceive(SceneContext.shared.$interfaceOrientation) { (orientation) in
        // do something with the new orientation
    }

    // if you want to execute some code whenever the orientation changes in a regular Swift object
    let pub = SceneContext.shared.$interfaceOrientation.sink(receiveValue: { (orientation) in
            // do something with the new orientation
            ...
        }) 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接