方向不会在第二次改变

时间:2014-12-05 16:24:09

标签: ios objective-c uiinterfaceorientation uidevice

我在下面有这个代码,可以识别设备何时改变方向,如果方向是左右横向,他又回到肖像:

    [[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"];
    }

}

当我运行项目并将设备的方向向右或向左更改为横向时,此代码会识别并将方向更改为纵向,但如果我将设备再次向左或向右旋转,则代码不起作用我的设备保持横向模式,为什么?以及如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

我不知道我是否正确但是尝试从viewWillAppear

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

}

答案 1 :(得分: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
}

答案 2 :(得分:0)

您应该使用标准方法(例如supportedInterfaceOrientationsshouldAutorotate)锁定控制器的旋转,而不是使用私有API并从AppStore中删除。

相关问题