Ios 我可以观察UIViewController何时更改界面方向吗?
如果我有一个指向UIViewController的指针,当它在不修改控制器代码的情况下更改interfaceOrientation时,是否可以通知我Ios 我可以观察UIViewController何时更改界面方向吗?,ios,cocoa-touch,Ios,Cocoa Touch,如果我有一个指向UIViewController的指针,当它在不修改控制器代码的情况下更改interfaceOrientation时,是否可以通知我 我的最佳选择是检测设备方向的变化,然后查看UIViewController是否将/已旋转(d)?您可以使用NSNotificationCenter: [[NSNotificationCenter defaultCenter] addObserver:self // put here the view controller which has to
我的最佳选择是检测设备方向的变化,然后查看UIViewController是否将/已旋转(d)?您可以使用NSNotificationCenter:
[[NSNotificationCenter defaultCenter] addObserver:self // put here the view controller which has to be notified
selector:@selector(orientationChanged:)
name:@"UIDeviceOrientationDidChangeNotification"
object:nil];
- (void)orientationChanged:(NSNotification *)notification{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
//do stuff
NSLog(@"Orientation changed");
}
您可以在UIViewController上使用
WillAnimateRotationInterfaceOrientation:duration:
方法,然后为横向或纵向重新定位任何UIView(或任何其他代码)。例如
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
// change positions etc of any UIViews for Landscape
} else {
// change position etc for Portait
}
// forward the rotation to any child view controllers if required
[self.rootViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
嗯,我想我不清楚。我想知道ViewController的外观方向,而不是设备。换句话说,我的对象希望观察视图控制器以查看其方向,该方向可能与设备的方向不同,并且在设备更改方向时可能不会更改。这个答案是我在问题的第二部分暗示的一部分。不幸的是,这意味着要更改UIViewController的代码。这里我只有一个指向它的指针,希望观察它的行为。我真正想做的是当“interfaceOrientation”返回不同的值时收到通知。注意:这在iOS 8中是不推荐的。不确定问题是否仍然存在,但可以使用objc方法swizzling将自己的代码添加到
UIViewController
的代码中。这看起来应该像是用自己的实现交换-didRotateFromInterfaceOrientation:
,该实现调用了orientation changed handler方法,并调用了originalimplementation@medvedNick这似乎是合理的。我可以调用我的委托,然后调用原始实现。我可能有点担心潜在的副作用。