iOS 强制横竖屏 Swift

本文分享了在iOS开发中如何使用Swift强制设置应用界面的横竖屏显示。通过修改AppDelegate类中的supportedInterfaceOrientationsFor函数,可以实现对特定页面如播放器的屏幕方向控制。同时提供了一个工具类,包含强制横屏和竖屏的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 你的上层级控制器
    }

在你的事件响应中,调用工具类中的函数就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值