1

我想检测设备的当前方向。

所以,我用了一行代码

注意:即使我没有注册它也会给我方向

-(IBAction) deviceOrientationChanged:(id) sender{
    NSLog(@"Device Orientation= %d",[[UIDevice currentDevice] orientation]);
}

当我更改方向时,在按钮单击事件中我得到设备方向。

但是,文档说你需要先注册它,然后使用上面的代码。

注意:在下面的代码中,我已注册设备以接收设备方向通知

-(IBAction) deviceOrientationChanged:(id) sender{

    if(![[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications]){
        //This statement is called very time when I click on the button. I expected to execute only once.
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    }
    NSLog(@"Device Orientation= %d",[[UIDevice currentDevice] orientation]);
}

所以,我无法通过完美的方式来获得设备方向。

4

3 回答 3

1

注册通知不同于生成通知。通常,如果您计划在应用程序委托中或在适当的位置使用设备方向通知,您将在 UIDevice 上调用 beginGeneratingDeviceOrientationNotifications,并在 U 不再需要通知时在另一个适当的位置调用 endGeneratingDeviceOrientationNotifications。这只是 deviceOrientaion 通知的初始设置。

要在您的控制器或对象中获得这些通知,您必须向我们通知中心。U注册通知UIDeviceOrientationDidChangeNotification。[[NSNotificationCenter defaultCenter] addObserver:myObject 选择器:@selector(deviceRotated:)name:UIDeviceOrientationDidChangeNotification object:nil]

当你不需要它或在对象的dealloc中将其从通知中心删除。

于 2012-12-20T17:27:54.150 回答
1

我认为你的 if 条件是错误的;你有它 if([[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications]) 它应该是

if( ! [[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications])

于 2012-12-18T23:48:51.727 回答
0

您无法阻止设备生成UIViewController轮播通知。请参阅此处的问题

您链接到的文档所指的是NSNotificationCenter通知。

于 2012-12-18T16:20:48.077 回答