繁体   English   中英

使用NSNotificationCenter和UIDeviceOrientation更改方向

[英]Change orientation with NSNotificationCenter and UIDeviceOrientation

当我在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");
    }
}

调用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方法在您的代码中orientacionActual ,没有任何意义。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM