ios橫豎屏轉換相關

一直想寫一篇關於屏幕旋轉的文章,最近抽出些時間整理了下之前項目用到的屏幕旋轉相關問題。
1.單個控制器開啓轉屏
2.自定義播放器橫屏時全屏,連接投影儀時手機橫屏,顯示也爲橫屏

單個控制器開啓轉屏 需配置以下幾點

在AppDelegate配置轉屏屬性

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 橫豎屏設置
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    [de setBool:NO forKey:@"SOrientations"];
    return YES;
}
// MARK: - 橫豎屏設置
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{

    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    bool a = [de boolForKey:@"SOrientations"];
    if (a == YES) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

在需要強制轉屏的控制器初始化時,配置轉屏

 override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let de = UserDefaults.standard
        de.set(true, forKey: "SOrientations")
   }

在需要強制轉屏的控制器消失時,取消轉屏配置

  override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        let de = UserDefaults.standard
        de.set(false, forKey: "SOrientations")
    }

到此,單個控制器允許轉屏已經完成

如果需要在轉屏時做一些操作,比如橫屏狀態下視頻全屏播放自定義播放器在連接投影儀,手機橫屏時投影儀也顯示橫屏

上面的代碼仍然會用到
另外需要,
在viewWillAppear中添加代碼

 let oritation = UIDevice.current.orientation        
 if(oritation == UIDeviceOrientation.landscapeLeft){
    Rotate_Angel = Double.pi / 2
   }
 UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        NotificationCenter.default.addObserver(self, selector: #selector(self.orientationChanged(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

在viewWillDisappear中添加代碼

 NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

orientationChanged中配置轉屏時播放器操作

 var Rotate_Angel: Double = Double.pi / 2
 var lastOritation = UIDeviceOrientation.portrait
 func orientationChanged(_ notification: Foundation.Notification) {

        let oritation = UIDevice.current.orientation
        print("orientationChanged:", oritation.rawValue)

        if(lastOritation == UIDeviceOrientation.portrait){
            if(oritation == UIDeviceOrientation.landscapeLeft){
                Rotate_Angel = Double.pi / 2
            }else if(oritation == UIDeviceOrientation.landscapeRight){
                Rotate_Angel = -Double.pi / 2
            }
        }
        if(oritation == UIDeviceOrientation.landscapeLeft || oritation == UIDeviceOrientation.landscapeRight){
            if(!isFullScreen){
                //進入全屏設置
                lastOritation = oritation
            }
        }else if(oritation == UIDeviceOrientation.portrait){
            if(isFullScreen){
                //返回豎屏設置
                lastOritation = oritation
            }
        }
    }

整個處理過程都在這裏了,供大家參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章