我对 objective c 还很陌生,所以我可能没看过这里的基本内容。我引用了一个 View Controller ,我希望此 View Controller 订阅/观察 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
的子类,并且在执行我的代码时已经初始化。因此,如果不执行类似类 eval 的操作,我就无法实现自己的 willAnimateRotaionToInterfaceOrientation
方法
最佳答案
通常,您实际上不需要注册任何通知。根据 Apple 关于 Supporting Multiple Interface Orientations 的文档:
When the orientation of an iOS–based device changes, the system sends out a UIDeviceOrientationDidChangeNotification notification to let any interested parties know that the change occurred. By default, the UIKit framework listens for this notification and uses it to update your interface orientation automatically. This means that, with only a few exceptions, you should not need to handle this notification at all.
上面的链接对如何正确处理设备旋转有非常清晰的解释,我建议你去看看。
一般来说,您应该为您需要的任何 View Controller 创建您自己的 UIViewController 子类。在您的 ViewController 子类中,只需实现以下方法,它应该在设备旋转时调用。
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInt
duration:(NSTimeInterval)duration;
如果出于某种原因子类化 View Controller 不是一个选项,那么您可以尝试使用“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
请注意,我很懒惰,并没有费心包含代码以在您不再需要时删除通知观察器,或者停止接收有关设备旋转的通知。
关于ios - 如何订阅 viewController 对 willAnimateRotationToInterfaceOrientation 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461354/