Capacitor調整APP螢幕方向的方法

Ted Yan
Nov 30, 2023

--

使用@capacitor/screen-orientation

安裝

npm install @capacitor/screen-orientation
npx cap sync

XCode設定

在AppDelegate.swift檔案中設定

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask(rawValue: (self.window!.rootViewController as! CAPBridgeViewController).supportedInterfaceOrientations.rawValue)
}

使用範例

import { Capacitor } from '@capacitor/core';
import { ScreenOrientation } from '@capacitor/screen-orientation';

// 確認是否為行動裝置
if (Capacitor.isNativePlatform()) {
// 將畫面固定為橫向
ScreenOrientation.lock({ orientation: 'landscape-primary' });
// 將畫面固定為縱向
ScreenOrientation.lock({ orientation: 'portrait-primary' });
}

參考資料

@capacitor/screen-orientation - Capacitor

Handling Screen Orientation Changes in Capacitor Apps

其他插件

@capawesome/capacitor-screen-orientation - GitHub

--

--

Ted Yan

網站工程師,使用過的程式語言有PHP、Javascript、Golang、C#,使用過的Framwork有Laravel、Vue、React Native、Gin,資料庫以MySQL為主,也曾接觸Elastic Search、Docker、AWS與GCP相關服務與應用