gpt4 book ai didi

ios - 在 Apple Watch 和 iPhone 上使用 SwiftUI 进行特定于设备的布局

转载 作者:可可西里 更新时间:2023-11-01 03:53:06 26 4
gpt4 key购买 nike

有时,我需要对布局进行特定于设备的调整。例如,我可能需要在屏幕较小的 iPhone 上缩小间距或在最大屏幕上增加间距。使用 UIKit(甚至是 Interface Builder),可以很容易地为特定大小的类创建布局异常。 使用 SwiftUI 进行条件设备特定布局的最佳方法是什么?

我一直在搜索 SwiftUI 文档,但没有找到在布局中访问和使用此类信息的方法。

下面是 Apple Watch 应用程序的示例。根据 Apple 的设计指南,我在 40mm Series 4 的左右两侧添加了 8.5 点的填充。但是,44mm 应该有 9.5 点的填充,任何早于 Series 4 的 Apple Watch 都应该没有填充。

使用 SwiftUI 实现此目标的最佳方法是什么?

struct ContentView : View {

var body: some View {
HStack {
Text("Hello World")
}.padding([.horizontal], 8.5)
}
}

最佳答案

一般来说,您可以使用两种方法来实现设备特定的布局:

  1. 通过@Environment 变量调整大小类
  2. GeometryReader 用于更细粒度的控制

不幸的是,UserInterfaceSizeClass 只有 .compact.regular,在 watchOS 上不可用。

使用环境:

struct MyView: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
}

要使用 GeometryReader:

var body -> some View {
GeometryReader { proxy in
if proxy.size.width > 324.0/2.0 { // 40mm watch resolution in points
MyBigView()
} else {
MySmallView()
}
}
}

作为引用,以下是 watch 分辨率:

  • 40mm: 394×324
  • 44mm: 448×368
  • 38mm: 340×272
  • 42mm: 390×312

除以 2.0 以而不是像素获取它们的值。

关于ios - 在 Apple Watch 和 iPhone 上使用 SwiftUI 进行特定于设备的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com