如何订阅viewController对willAnimateRotationToInterfaceOrientation的引用

时间:2013-12-09 00:57:25

标签: ios objective-c ios7

我对目标c很陌生,所以我可能会在这里寻找基本的东西。我引用了一个视图控制器,我希望这个视图控制器能够订阅/观察willAnimateRotationToInterfaceOrientation的处理程序。我的代码如下所示。

UIViewController* globalVC

@implementation my_API

+ (void)render:(){
    [[NSNotificationCenter defaultCenter] addObserver:globalVC selector:@selector(willAnimateRotationToInterfaceOrientation:duration:) name:@"willAnimateRotationToInterfaceOrientation" object:nil];

}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInt
                                        duration:(NSTimeInterval)duration {

  //do some stuff

}

目前使用此设置时,willAnimateRotationToInterfaceOrientation方法永远不会被触发。

编辑:

让我补充一点:我的globalVC来自第三方图书馆(想想横幅广告或其他内容)。这已经是UIViewController的子类,并且在我的代码执行时已经初始化了。因此,我无法实现自己的willAnimateRotaionToInterfaceOrientation方法,而无需像类eval那样做

1 个答案:

答案 0 :(得分:2)

通常,您实际上不需要注册任何通知。根据Apple Supporting Multiple Interface Orientations的文档:

  

当基于iOS的设备的方向发生变化时,系统会发送   输出一个UIDeviceOrientationDidChangeNotification通知让任何   有兴趣的人知道发生了变化。默认情况下   UIKit框架侦听此通知并使用它进行更新   您的界面方向自动。这意味着,只有一个   少数例外,您不应该在此处理此通知   所有

上面的链接对如何正确处理设备旋转有一个非常明确的解释,我建议你看一下。

通常,您应该为您需要的任何视图控制器创建自己的UIViewController子类。在ViewController子类中,只需实现以下方法,并应在设备轮换时调用它。

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInt
                                    duration:(NSTimeInterval)duration;

如果由于某种原因继承视图控制器的子类,则可以尝试使用“UIDeviceOrientationDidChangeNotification”从其他位置处理设备旋转。但是,在此之前,您还需要告诉您的设备您希望接收这些通知。例如:

@implementation MyRotationController

-(void) setupMyRotationController {

    [UIDevice beginGeneratingDeviceOrientationNotifications]
    [[NSNotificationCenter defaultCenter] addObserver:self
                             selector:@selector(orientationChanged:)
                             name:UIDeviceOrientationDidChangeNotification
                             object:nil];
}

- (void)orientationChanged:(NSNotification *)notification
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (UIDeviceOrientationIsLandscape(deviceOrientation))
    {
        //do something
    }
    else if (UIDeviceOrientationIsPortrait(deviceOrientation) &&
             isShowingLandscapeView)
    {
        //do something else
    }
}


@end

注意,我很懒,并且没有费心包括在您不再需要时删除通知观察者的代码,或者停止获取有关设备轮换的通知。

相关问题