如何检测屏幕方向变化?

173

我正在使用Swift,当我旋转到横向模式时,我想要能够加载一个UIViewController,有人可以指点我一下吗?

我在网上找不到任何信息,对文档感到有点困惑。


1
我猜API没有改变,所以应该是“didRotateToOrientation”和“willRotateToOrientation”,类似这样的东西,请查看苹果文档。 - David Ansermot
1
嗨@mArm.ch,感谢您的快速回复!那么我该如何实现呢?(这是我的第一个应用程序...我对IOS非常陌生) :) - David
我将其转发为答案,供其他人参考。如果您觉得可以的话,您能否接受它? - David Ansermot
如果您想在应用程序启动时检查方向,请检查此内容。 https://dev59.com/clsW5IYBdhLWcg3w7KtL#49058588 - eharo2
24个回答

1

iOS 13.1.2版本中,设备方向始终返回0,直到设备被旋转。在任何旋转事件发生之前,我需要调用UIDevice.current.beginGeneratingDeviceOrientationNotifications()方法以获取实际的旋转方向。


1
对于Swift 3
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        //Landscape
    }
    else if UIDevice.current.orientation.isFlat {
        //isFlat
    }
    else {
        //Portrait
    }
}

你忘记了 UIDevice.current.orientation.isFlat - user924

0
- (void)viewDidLoad {
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

-(void)OrientationDidChange:(NSNotification*)notification {
  UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];

  if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight) {
    NSLog(@"Landscape");
  } else if(Orientation==UIDeviceOrientationPortrait) {
    NSLog(@"Potrait Mode");
  }
}

注意:只需使用此代码来确定UIViewController处于哪个方向


你的代码在项目中无法运行。我还需要做其他什么吗? - Syed Ali Salman

0
override func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(MyController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
//...
}

@objc
private func rotated() {
    if UIDevice.current.orientation.isLandscape {

    } else if UIDevice.current.orientation.isPortrait {

    }

    //or you can check orientation separately UIDevice.current.orientation
    //portrait, portraitUpsideDown, landscapeLeft, landscapeRight... 

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接