关键代码:
添加检测设备方向的通知:
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
}
let interfaceOrientation:
UIInterfaceOrientation =
UIInterfaceOrientation(rawValue: orientation
.rawValue)!
switch interfaceOrientation {
case UIInterfaceOrientation.portraitUpsideDown:
break
case UIInterfaceOrientation.portrait:
toOrientation(orientation:
UIInterfaceOrientation.portrait);
break
case UIInterfaceOrientation.landscapeLeft:
toOrientation(orientation:
UIInterfaceOrientation.landscapeLeft);
break
case UIInterfaceOrientation.landscapeRight:
toOrientation(orientation:
UIInterfaceOrientation.landscapeRight);
break
default:
break
}
}
private func toOrientation(orientation:
UIInterfaceOrientation) {
let currentOrientation =
UIApplication.shared.statusBarOrientation
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效果:
DEMO完整代码
转载请注明原文地址: https://ju.6miu.com/read-32755.html