|
iOS Swift3.0实现视频播放横竖屏切换效果
关键代码:添加检测设备方向的通知:
- UIDevice.current.beginGeneratingDeviceOrientationNotifications()
- // 检测设备方向
- NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
复制代码 设备方向改变调用:
- /// 设备方向改变
- @objc fileprivate func deviceOrientationChange() {
- // 获取当前设备方向
- let orientation = UIDevice.current.orientation
- // 如果手机硬件屏幕朝上或者屏幕朝下或者未知
- if orientation == UIDeviceOrientation.faceUp || orientation == UIDeviceOrientation.faceDown || orientation == UIDeviceOrientation.unknown {
- return
- }
- // UIDeviceOrientation 和 UIInterfaceOrientation 方向转换
- let interfaceOrientation: UIInterfaceOrientation = UIInterfaceOrientation(rawValue: orientation.rawValue)!
- switch interfaceOrientation {
- //屏幕竖直,home键在上面
- case UIInterfaceOrientation.portraitUpsideDown: break
- //屏幕竖直,home键在下面
- case UIInterfaceOrientation.portrait:
- toOrientation(orientation: UIInterfaceOrientation.portrait); break
- //屏幕水平,home键在左
- case UIInterfaceOrientation.landscapeLeft:
- toOrientation(orientation: UIInterfaceOrientation.landscapeLeft); break
- //屏幕水平,home键在右
- case UIInterfaceOrientation.landscapeRight:
- toOrientation(orientation: UIInterfaceOrientation.landscapeRight); break
- default:
- break
- }
- }
- /// 旋转
- private func toOrientation(orientation: UIInterfaceOrientation) {
- //获取当前状态栏的方向
- let currentOrientation = UIApplication.shared.statusBarOrientation
- //如果当前的方向和要旋转的方向一致,直接return
- if currentOrientation == orientation {
- return
- }
- //根据要旋转的方向,重新布局
- if orientation != UIInterfaceOrientation.portrait {
- // 从全屏的一侧直接到全屏的另一侧不修改
- if currentOrientation == UIInterfaceOrientation.portrait {
- label.snp.makeConstraints({ (make) in
- make.width.equalTo(UIScreen.main.bounds.size.height)
- make.height.equalTo(UIScreen.main.bounds.size.width)
- make.center.equalTo(UIApplication.shared.keyWindow!)
- })
- }
- }
- //状态栏旋转
- UIApplication.shared.setStatusBarOrientation(orientation, animated: false)
- UIView.beginAnimations(nil, context: nil)
- UIView.setAnimationDuration(0.35)
- label.transform = CGAffineTransform.identity
- label.transform = getTransformRotationAngle()
- UIView.commitAnimations()
- }
- /// 获取旋转角度
- private func getTransformRotationAngle() -> CGAffineTransform {
- let interfaceOrientation = UIApplication.shared.statusBarOrientation
- if interfaceOrientation == UIInterfaceOrientation.portrait {
- return CGAffineTransform.identity
- } else if interfaceOrientation == UIInterfaceOrientation.landscapeLeft {
- return CGAffineTransform(rotationAngle: (CGFloat)(-M_PI_2))
- } else if (interfaceOrientation == UIInterfaceOrientation.landscapeRight) {
- return CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
- }
- return CGAffineTransform.identity
- }
复制代码
- 在Info.plist中通添加View controller-based status bar appearance并设置值为NO(why)
复制代码
Demo效果:
|
|