SwiftUI iPadOS 应用程序根据方向更改文本

sug*_*ode 1 text device-orientation swiftui

我想根据设备方向更改显示的文本。视觉将描述我正在努力实现更好的目标:)

这里是横向模式 横向模式 这是纵向模式 纵向模式

我想在纵向模式下显示月份名称的短格式,并找到了各种描述如何通过检测设备方向来实现这一点的帖子。我还发现这不在最佳实践类别中,所以想知道是否有更好的方法。代码只是一个 VStack,在 ScrollView 中有两个 Text 组件。

Kev*_*ers 8

我会稍微改变接受的答案,而不是使用.onReceive

.onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in
  self.orientation = UIDevice.current.orientation
}
Run Code Online (Sandbox Code Playgroud)

这应该自动处理取消订阅。


Jef*_*son 7

SwiftUI 似乎没有约束或约束变体,就像界面构建器针对方向所做的那样。我认为目前还没有既定的最佳实践。我会毫不犹豫地使用方向值,直到出现可以让我们更好地对方向变化做出反应的东西。

我可能会做这样的事情来对方向做出反应:

[更新@kevin-renskers 改进]

struct ContentView: View {
    @State var orientation: UIDeviceOrientation = UIDevice.current.orientation
    
    var body: some View {
        Text(orientation.isLandscape ? "Landscape" : "Portrait")
        .onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in
          self.orientation = UIDevice.current.orientation
        }
    }
}
Run Code Online (Sandbox Code Playgroud)