我正在使用viewWillTransitionToSize来检测设备何时旋转到横向。根据目标大小,我可以检测是否前往景观并根据需要调整我的特征......
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if size.width > size.height {
self.setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.Regular), forChildViewController: viewController)
}
else{
self.setOverrideTraitCollection(nil, forChildViewController: viewController)
}
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}
但是,我希望能够检测我的设备是转换为横向左侧还是横向右侧。这将允许我根据设备的具体方向创建不同的行为或视图。 (左或右)。
如果不使用任何已弃用的函数,是否可以这样做?
我想过使用状态栏方向......
let orientation = UIApplication.sharedApplication().statusBarOrientation;
if( orientation == UIInterfaceOrientation.LandscapeLeft )
{
// Do something
}
else if( orientation == UIInterfaceOrientation.LandscapeRight )
{
// Do something else
}
...但这没有用,因为这似乎会给出“旧”状态。
如何获得特定的目标定位?
答案 0 :(得分:14)
您可以在旋转使用UIViewControllerTransitionCoordinator
时获得方向,如下所示:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// will execute before rotation
coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in
// will execute during rotation
let orientation = UIApplication.shared.statusBarOrientation
if orientation == .landscapeLeft
{
// Do something
}
else if orientation == .landscapeRight
{
// Do something else
}
}) { (context: UIViewControllerTransitionCoordinatorContext) in
// will execute after rotation
}
}
答案 1 :(得分:-2)
使用[UIDevice currentDevice].orientation