Ios 方向不';不要在第二时间改变

Ios 方向不';不要在第二时间改变,ios,objective-c,uiinterfaceorientation,uidevice,Ios,Objective C,Uiinterfaceorientation,Uidevice,我有下面的代码,可以识别设备何时改变方向,如果方向是横向左侧或右侧,他将再次返回到纵向: [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrie

我有下面的代码,可以识别设备何时改变方向,如果方向是横向左侧或右侧,他将再次返回到纵向:

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

}

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

我不知道我是否正确,但尝试从视图中触发您的通知将出现

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

}

更好的做法是在
视图中注册通知,然后在
视图中取消注册。这样,您将仅在视图显示时捕获通知

执行类似于:

-(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];
}
如果
UIDeviceOrientationIDChangeNotification
不能解决您的问题,请尝试如下状态BarOrientationNotification

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

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

    // handle changes
}

不要弄乱私有API并被AppStore拒绝,您只需使用标准方法锁定控制器的旋转,例如
supportedInterfaceOrientations
shouldAutorotate