提问者:小点点

基于设备旋转更新变量-Swift UI


null

null

    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")
        }
    }
}

null

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
    }
}

共1个答案

匿名用户

null

  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
    }
    
    }

null

相关问题