1.首先在Xcode工程设定中,确认横屏和竖屏都是打开的。
2.在AppDelegate中。
//当前界面支持的方向(默认情况下只能竖屏,不能横屏显示)
var interfaceOrientations:UIInterfaceOrientationMask = .portrait{
didSet{
//强制设置成竖屏
if interfaceOrientations == .portrait{
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue,
forKey: "orientation")
}
//强制设置成横屏
else if !interfaceOrientations.contains(.portrait){
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue,
forKey: "orientation")
}
}
}
//返回当前界面支持的旋转方向
func application(_ application: UIApplication, supportedInterfaceOrientationsFor
window: UIWindow?)-> UIInterfaceOrientationMask {
return interfaceOrientations
}
3.在swiftUI的View画面中,可以控制横屏和竖屏幕变换。
struct XXXXXView: View {
var body: some View {
ZStack(alignment: .bottom) {
xxxxxxx
}.frame(alignment: .bottom)
.onAppear() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.interfaceOrientations = [.landscapeRight]
}.onDisappear() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.interfaceOrientations = .portrait
}
}