使用NSNotificationCenter和UIDeviceOrientation更改方向

时间:2014-01-16 18:03:44

标签: ios orientation nsnotificationcenter 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");
    }
}

1 个答案:

答案 0 :(得分:6)

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

内部viewDidLoad:

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

及以下:

- (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");
    }
}

orientacionActual方法减少代码,并没有任何意义。

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