使用NSNotificationCenter和UIDeviceOrientation更改方向

use*_*911 1 orientation nsnotificationcenter ios landscape-portrait

当我在xCode中更改模拟器的方向时,为什么不工作?我看到ViewController上的标签始终等于并且NSLog没有出现.

ViewController.m:

- (void)viewDidLoad
{
    [self orientacionActual];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientacionActual)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIDeviceOrientation) orientacionActual
{
    UIDeviceOrientation orientacionActual = [UIDevice currentDevice].orientation;
    return orientacionActual;
}

- (void) cambiaOrientacion:(NSNotification *) notificación
{
    if(UIDeviceOrientationIsLandscape([self orientacionActual]))
    {
        self.LabelEstoy.text = @"Landscape";
        NSLog(@"Landscape");
    } else if (UIDeviceOrientationIsPortrait([self orientacionActual]))
    {
        self.LabelEstoy.text = @"Portrait";
        NSLog(@"Portrait");
    }
}
Run Code Online (Sandbox Code Playgroud)

Alm*_*ali 6

调用UIApplicationDidChangeStatusBarOrientationNotification而不是设备方向更改.另外,我不确定您的目标是什么,但请尝试使用此代码段:

viewDidLoad:

    [[NSNotificationCenter defaultCenter] addObserver:self 
                      selector:@selector(cambiaOrientacion:)
                          name:UIApplicationDidChangeStatusBarOrientationNotification
                        object:nil];
Run Code Online (Sandbox Code Playgroud)

及以下:

- (void)cambiaOrientacion:(NSNotification *)notificacion
{
    UIInterfaceOrientation orientation = [[[notification userInfo] 
       objectForKey:UIApplicationStatusBarOrientationUserInfoKey] integerValue];
    if (UIInterfaceOrientationIsLandscape(orientation))
    {
        self.LabelEstoy.text = @"Landscape";
        NSLog(@"Landscape");
    } else
    {
        self.LabelEstoy.text = @"Portrait";
        NSLog(@"Portrait");
    }
}
Run Code Online (Sandbox Code Playgroud)

orientacionActual代码中的方法redudant,没有任何意义.

不要忘记添加[[NSNotificationCenter defaultCenter] removeObserver:self]内部dealloc.