我试图找到一个方法调用,一旦设备的方向发生变化,我就可以锁定它。有没有与didRotateFromInterfaceOrientation相同的东西不被弃用?
答案 0 :(得分:27)
从iOS 8开始,所有UIViewControllers都继承了UIContentContainer协议,其中一种方法是- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
,你可以(简单地)覆盖这样:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Stuff you used to do in willRotateToInterfaceOrientation would go here.
// If you don't need anything special, you can set this block to nil.
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Stuff you used to do in didRotateFromInterfaceOrientation would go here.
// If not needed, set to nil.
}];
}
你会注意到,没有具体的定位,这是设计的; iOS视图旋转本质上是特定平移矩阵操作的组合(将视图从一个宽高比调整为另一个只是一般调整大小操作的特定情况,其中源视图大小和目标视图大小是预先知道的)和旋转矩阵操作(由操作系统处理)。
答案 1 :(得分:3)
swift 3 版本的fullofsquirrels的答案:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { context in
context.viewController(forKey: UITransitionContextViewControllerKey.from)
// Stuff you used to do in willRotateToInterfaceOrientation would go here.
// If you don't need anything special, you can set this block to nil.
}, completion: { context in
// Stuff you used to do in didRotateFromInterfaceOrientation would go here.
// If not needed, set to nil.
})
}
答案 2 :(得分:2)
您可以随时注册UIDeviceOrientationDidChangeNotification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didRotate:)
name:UIDeviceOrientationDidChangeNotification object:nil];
- (void) didRotate:(id)sender
{
UIInterfaceOrientation io = [[UIApplication sharedApplication] statusBarOrientation];
...