LoginSignup
1
2

Swiftアプリプレイグラウンド(.swiftpm)で画面回転をロックする

Posted at

画面回転をロックしよう

通常のプロジェクトであれば
Generalタブ > Deployment info > Device Orientation
でロックできます。
ただアプリプレイグラウンドでないと提出できないようなコンテストなど用にコードで回転をロックするのを書いときます。

ContentView.swift
import SwiftUI
import UIKit

// UIViewControllerを拡張して、特定の向きを設定
extension UIViewController {
    func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    // 任意のビューで特定の向きを設定するためのメソッド
    func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }
}

// AppDelegateでの設定
class AppDelegate: UIResponder, UIApplicationDelegate {
    var orientationLock = UIInterfaceOrientationMask.all

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return orientationLock
    }
}

// SwiftUIビューで使用
struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .onAppear {
                // ここでポートレートにロックする
                UIViewController().lockOrientation(.portrait, andRotateTo: .portrait)
            }
            .onDisappear {
                // 画面が消えるときにロックを解除
                UIViewController().lockOrientation(.all)
            }
    }
}

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2