我想呈现一个响应方向变化的视图,但由于各种原因不能使用 iOS 的内置自动旋转。在viewDidLoad
我使用当前方向来确定视图的初始布局:
_originalOrientation = [UIDevice currentDevice].orientation;
// if we were launched flat or unknown, use the status bar orientation as a guide
if (_originalOrientation == UIDeviceOrientationUnknown ||
_originalOrientation == UIDeviceOrientationFaceDown ||
_originalOrientation == UIDeviceOrientationFaceUp) {
_originalOrientation = UIDeviceOrientationFromInterfaceOrientation([UIApplication sharedApplication].statusBarOrientation);
}
正如您从我的评论中看到的那样,我需要处理[UIDevice currentDevice].orientation
不是可用方向的情况(即设备是平的或处于未知方向)。在这种情况下,我尝试使用statusBarOrientation
来推断设备的方向(使用UIViewController
'sinterfaceOrientation
将是获取相同信息的另一种方法):
UIDeviceOrientation UIDeviceOrientationFromInterfaceOrientation(UIInterfaceOrientation interface) {
// note: because UIInterfaceOrientationLandscapeLeft and UIInterfaceOrientationLandscapeRight have the same value, this conversion can't distinguish them
if (interface == UIInterfaceOrientationLandscapeLeft) {
return UIDeviceOrientationLandscapeLeft;
} else if (interface == UIInterfaceOrientationLandscapeRight) {
return UIDeviceOrientationLandscapeRight;
} else if (interface == UIInterfaceOrientationPortraitUpsideDown) {
return UIDeviceOrientationPortraitUpsideDown;
} else {
return UIDeviceOrientationPortrait;
}
}
但是我的逻辑无法准确辨别这两种景观情况,因为它们被定义UIApplication.h
为相同的常数值:
// Note that UIInterfaceOrientationLandscapeLeft is equal to UIDeviceOrientationLandscapeRight (and vice versa).
// This is because rotating the device to the left requires rotating the content to the right.
typedef NS_ENUM(NSInteger, UIInterfaceOrientation) {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft
};
有没有另一种方法可以区分UIInterfaceOrientationLandscapeLeft
和UIInterfaceOrientationLandscapeRight
?除了使用状态栏方向之外,我还有更好的方法来执行我的“后备”逻辑吗?