簡體   English   中英

基於設備旋轉更新變量 - Swift UI

[英]Update variables based on device rotation - Swift UI

我找到並使用了一些代碼,這些代碼將根據設備大小和旋轉返回一個變量 true。 然而,當設備旋轉時,這些變量不會更新,文本也不會改變。 我想我需要使用可觀察的 object 但我不確定 go 如何轉換此擴展名? 這是我在下面使用的代碼。

內容視圖()

    struct ContentView3: View, SizeClassAdjustable {
    
    @Environment(\.verticalSizeClass) var _verticalSizeClass
    @Environment(\.horizontalSizeClass) var _horizontalSizeClass
    var verticalSizeClass: UserInterfaceSizeClass? { _verticalSizeClass }
    var horizontalSizeClass: UserInterfaceSizeClass? { _horizontalSizeClass }
    
    var body: some View {
        if(self.isPadLandscape){
            Text("iPad Landscape")
        }else if(self.isPadPortrait){
            Text("iPad Portrait")
        }else if(self.isPortrait){
            Text("iPhone Portrait")
        }else if(self.isLandscape){
            Text("iPhone Landscape")
        }
    }
}

擴展:

protocol SizeClassAdjustable {
    var verticalSizeClass: UserInterfaceSizeClass? { get }
    var horizontalSizeClass: UserInterfaceSizeClass? { get }
}
extension SizeClassAdjustable {
    
    var isPad: Bool {
        return horizontalSizeClass == .regular && verticalSizeClass == .regular
    }
    var isPadLandscape: Bool {
        isPad && UIDevice.current.orientation.isLandscape
    }
    var isPadPortrait: Bool {
        isPad && UIDevice.current.orientation.isPortrait
    }
    var isPadOrLandscapeMax: Bool {
        horizontalSizeClass == .regular
    }
    var isLandscapeMax: Bool {
        horizontalSizeClass == .regular && verticalSizeClass == .compact
    }
    var isLandscape: Bool {
        verticalSizeClass == .compact
    }
    var isPortrait: Bool {
        verticalSizeClass == .regular
    }
}

檢查設備是否處於縱向或橫向模式,如下所示:

let screen = UIScreen.main.bounds

if UIDevice.current.userInterfaceIdiom == .phone{ //Phone

    if screen.width < screen.height { //Portrait
    } else { //Landscape
    }

} else { //iPad

    if screen.width < screen.height { //Portrait
    } else { //Landscape
    }

}

然后在正確的 scope 中執行您的操作。
記得導入 UIKit 來使用這個方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM