首页 > 解决方案 > 在 Apple Watch 和 iPhone 上使用 SwiftUI 进行设备特定布局

问题描述

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

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

以下是 Apple Watch 应用程序的示例。根据 Apple 的设计指南,我在 40 毫米系列 4 的左侧和右侧添加了 8.5 个填充点。但是,44 毫米应该有 9.5 个填充点,任何比系列 4 更早的 Apple Watch 都应该没有填充。

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

struct ContentView : View {

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

标签: iosapple-watchswiftuiwatchos

解决方案


In general there are two methods you can use to achieve device specific layouts:

  1. Size classes via @Environment variables
  2. GeometryReader for more fine-grained control

Unfortunately, UserInterfaceSizeClass only has .compact and .regular and is not available on watchOS.

To use the environment:

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

To use GeometryReader:

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

For reference, here are the watch resolutions:

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

Divide by 2.0 to get their values in points instead of pixels.


推荐阅读