【发布时间】:2025-12-02 08:35:02
【问题描述】:
如何获取 iPhone 的当前方向? 我浏览了这个网站,发现了以下两种方法。
- [UIApplication sharedApplication].statusBarOrientation;
- [[UIDevice currentDevice] 方向];
获取当前方向的正确方法是哪一种? 我在模拟器4.1下尝试了两种方法,但是两种方法都存在一些问题。
【问题讨论】:
标签: iphone cocoa-touch
如何获取 iPhone 的当前方向? 我浏览了这个网站,发现了以下两种方法。
获取当前方向的正确方法是哪一种? 我在模拟器4.1下尝试了两种方法,但是两种方法都存在一些问题。
【问题讨论】:
标签: iphone cocoa-touch
注册你的类来监听 UIDeviceOrientationDidChangeNotification 然后相应地处理设备方向。
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(deviceRotated:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
并正确处理设备的方向:
- (void)deviceRotated: (id) sender{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationFaceUp ||
orientation == UIDeviceOrientationFaceDown)
{
//Device rotated up/down
}
if (orientation == UIDeviceOrientationPortraitUpsideDown)
{
}
else if (orientation == UIDeviceOrientationLandscapeLeft)
{
}
else if (orientation == UIDeviceOrientationLandscapeRight)
{
}
}
【讨论】:
[[UIDevice currentDevice] orientation] 获取设备的当前物理方向。 [UIApplication sharedApplication].statusBarOrientation 获取 UI 的方向。如果应用程序曾经向 shouldAutorotateToInterfaceOrientation: 方法返回 NO,则这两个值将不相同。
【讨论】:
[[UIDevice currentDevice] orientation] 可能不会返回您想要的值。我有一个界面,我根据用户输入动态布局,当我使用它时,我觉得很奇怪。使用statusBarOrientation 似乎效果很好。