[英]Update variables based on device rotation - Swift UI
I have found and used some code which will return a variable true based on the device size and rotation.我找到并使用了一些代码,这些代码将根据设备大小和旋转返回一个变量 true。 However these variables do not update when the device is rotated, and the text does not change.
然而,当设备旋转时,这些变量不会更新,文本也不会改变。 I think I would need to use an observable object but am not sure how I would go about converting this extension?
我想我需要使用可观察的 object 但我不确定 go 如何转换此扩展名? Here is the code I am using below.
这是我在下面使用的代码。
ContentView()内容视图()
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")
}
}
}
The Extension:扩展:
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
}
}
Check if the deices are in portrait or landscape mode like this:检查设备是否处于纵向或横向模式,如下所示:
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
}
}
Then perform your actions in the proper scope.然后在正确的 scope 中执行您的操作。
Remember to import UIKit to use this method.记得导入 UIKit 来使用这个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.