iOS:如何在设备旋转后运行一个函数(Swift)
我有一个没有使用自动布局的UIView,有些组件是根据主视图中X和Y坐标的百分比来显示的。
以前我会运行一个函数来更新他们在didRotateFromInterfaceOrientation中的位置,但是我发现现在在iOS8中已经弃用了它。
我已经看过viewWillTransitionToSize,但它给出了奇怪的结果,并没有看起来是一个viewDidtransitionToSize函数。
有一个简单的方法(在Swift中)在设备旋转后运行一个函数吗?
viewWillTransitionToSize
委托方法被调用UIViewControllerTransitionCoordinator
符合对象。 协议声明的方法是animateAlongsideTransition(_:animation, completion:)
。 您可以使用它来在转换完成后执行代码。
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil, completion: { _ in // Your code here }) }
以上回答https://stackoverflow.com/a/26944087/6583492是绝对正确的,感谢Acey和Moonwalkr。 但是对于swift 3.0,它看起来像下面这样
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil) { _ in // Your code here } }
虽然在这里没有要求Objective C版本:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { // change any properties on your views } completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { UIDeviceOrientation orientation = [UIDevice currentDevice].orientation; if( UIDeviceOrientationIsPortrait(orientation) ) { NSLog(@"portrait"); } else { NSLog(@"landscape"); } }]; }