iOS 强制横竖屏 Swift
在我们的开发过程中,大部分的app开发者是会把xcode中的横竖屏关掉的,但是我们会遇到某些页面需要强制横竖屏,比如说播放器,这里就向大家分享下swift强制横竖屏
首先找到我们的AppDelegate类,supportedInterfaceOrientationsFor函数中授权
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var isForceLandscape:Bool = false
var isForcePortrait:Bool = false
var isForceAllDerictions:Bool = false //支持所有方向
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
/// 设置屏幕支持的方向
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if isForceAllDerictions == true {
return .all
} else if isForceLandscape == true {
return .landscape
} else if isForcePortrait == true {
return .portrait
}
return .portrait
}
}
然后我们写一个工具类
class TempTool : NSObject {
// 强制旋转横屏
static func forceOrientationLandscape() {
let appdelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.isForceLandscape = true
appdelegate.isForcePortrait = false
_ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: TempTool.topViewController?.view.window)
let oriention = UIInterfaceOrientation.landscapeRight // 设置屏幕为横屏
UIDevice.current.setValue(oriention.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
}
// 强制旋转竖屏
static func forceOrientationPortrait() {
let appdelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.isForceLandscape = false
appdelegate.isForcePortrait = true
_ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: TempTool.topViewController?.view.window)
let oriention = UIInterfaceOrientation.portrait // 设置屏幕为竖屏
UIDevice.current.setValue(oriention.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
}
}
//获取最上层的控制器
static var topViewController :UIViewController?{
return 你的上层级控制器
}
在你的事件响应中,调用工具类中的函数就可以了