2014-12-05 67 views
-1

我有下面这段代码,当设备改变自己的方向承认,如果方向是横向向左或向右,他再次回到肖像:方向不第二次改变

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 

    [[NSNotificationCenter defaultCenter] 
    addObserver:self selector:@selector(orientationChanged:) 
    name:UIDeviceOrientationDidChangeNotification 
    object:[UIDevice currentDevice]]; 


- (void) orientationChanged:(NSNotification *)note{ 

    UIDevice * device = note.object; 

    if(device.orientation == UIDeviceOrientationLandscapeRight){ 


     [[UIDevice currentDevice] setValue: 
     [NSNumber numberWithInteger: UIInterfaceOrientationPortrait] 
            forKey:@"orientation"]; 
    } 

    if(device.orientation == UIDeviceOrientationLandscapeLeft){ 


     [[UIDevice currentDevice] setValue: 
     [NSNumber numberWithInteger: UIInterfaceOrientationPortrait] 
            forKey:@"orientation"]; 
    } 

} 

当我运行我的项目并将设备的方向改变为左右风景,此代码识别并将方向改为肖像,但是如果我再次将设备旋转到左右风景,则代码不起作用,设备停留在风景模式下,为什么?以及如何解决这个问题?

回答

0

我不知道如果我是正确的,但试图从viewWillAppear中

-(void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillAppear] ; 
    [[NSNotificationCenter defaultCenter] 
addObserver:self selector:@selector(orientationChanged:) 
name:UIDeviceOrientationDidChangeNotification 
object:[UIDevice currentDevice]]; 

} 
0

解雇的通知,是更好的做法是注册在viewWillAppear的通知,并在viewWillDisappear方法注销。因此,只有当您的观点呈现时才会收到通知。

实现诸如:

-(void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear] ; 
    [[NSNotificationCenter defaultCenter] 
    addObserver:self selector:@selector(orientationChanged:) 
    name:UIDeviceOrientationDidChangeNotification 
    object:[UIDevice currentDevice]]; 
} 

-(void)viewWillDisappear:(BOOL)animated 
{ 
    // Removing observer for lead created notification 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

如果UIDeviceOrientationDidChangeNotification没有解决您的问题,请尝试StatusBarOrientationNotification像如下。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; 

- (void)statusBarOrientationChange:(NSNotification *)note { 
    UIInterfaceOrientation orientation = [note.userInfo[UIApplicationStatusBarOrientationUserInfoKey] integerValue]; 

    // handle changes 
} 
0

而是与私人API和搞乱获得从苹果商店里拒绝了,你应该使用标准方法,如supportedInterfaceOrientationsshouldAutorotate控制器只需锁定旋转。