Как программно установить ориентацию интерфейса в SwiftUI - PullRequest
0 голосов
/ 14 апреля 2020

Для моей игровой логики c мне нужно заблокировать ориентацию экрана и установить ориентацию, программно запускаемую кнопкой в ​​SwiftUI. Как мне быть?

Ответы [ 2 ]

1 голос
/ 14 апреля 2020
import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: {
            self.rotate()
        }) {
            Text("Rotate")
        }
    }

    func rotate() -> Void {
        let value = UIInterfaceOrientation.landscapeRight.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }
}
0 голосов
/ 14 апреля 2020

Мое решение здесь, но мне интересно, есть какой-то лучший метод.

import SwiftUI
class HostVC<T>: UIHostingController<T> where T: View {
    override var shouldAutorotate: Bool {ContentView.autoRotate}
}
struct ContentView: View {
    static var autoRotate: Bool = false
    var body: some View {
        Button("Rotate") {
            let r: Int
            switch UIDevice.current.value(forKey: HomeView.keyOrientation) {
            case let i as Int where i == UIInterfaceOrientation.landscapeRight.rawValue: r = UIInterfaceOrientation.landscapeLeft.rawValue
            default: r = UIInterfaceOrientation.landscapeRight.rawValue
            }
            ContentView.autoRotate = true
            UIDevice.current.setValue(r, forKey: HomeView.keyOrientation)
            ContentView.autoRotate = false
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...