我正在使用SwiftUI,并尝试根据方向获取正确的屏幕尺寸。该解决方案可以在iPhone上的模拟器中正常运行,但在iPad上则无法使用(我没有用于真实测试的iPad)。在iPad上似乎只是缺少重绘事件。SwiftUI中是否有错误,还是我需要添加一些代码?
struct ContentView: View {
@Environment(\.layoutDirection) var layoutDir
// verticalSizeClass initiate redrawing UI based on new direction (horSizeClass won't work)
@Environment(\.verticalSizeClass) var vertSizeClass
var body: some View {
VStack{
Text("UIDevice.current.orientation").font(.title)
if UIDevice.current.orientation.isPortrait {
Text("Portrait")
} else if UIDevice.current.orientation.isLandscape {
Text("Landscape")
} else if UIDevice.current.orientation.isFlat {
Text("is Flat")
}
Text("UIScreen.main.bounds").font(.title)
Text("Width:\(UIScreen.main.bounds.width)")
Text("Height:\(UIScreen.main.bounds.height)")
Text("@Environment(\\.horizontalSizeClass").font(.title)
if vertSizeClass == .regular {
Text("regular")
} else if vertSizeClass == .compact {
Text("compact")
} else {
Text("default")
}
}
}
}
经测试,在iPad设备上不更新。请参阅以下评论/解决方案“ SwiftUI-确定当前设备和方向”:https://forums.developer.apple.com/thread/126878