3.11 SwiftUI 布局总结


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fileprivate struct ViewTransforming: View {
  @State private var aspectRatio: CGFloat = 1.0
  
  var body: some View {
    GroupBox("aspectRatio") {
      Rectangle()
        .fill(.blue.gradient)
        .aspectRatio(aspectRatio, contentMode: .fit)
        .frame(width: 80)
      LabeledContent("aspectRatio: \(aspectRatio, specifier: "%.1f")") {
        Slider(value: $aspectRatio, in: 0.5...2.0)
      }
    }
  }
}

https://stackoverflow.com/questions/57243677/proportional-height-or-width-in-swiftui

静态渲染适用于轻量的数据展示,比如 HStack、Grid 等,它们的内容和尺寸都相对固定。SwiftUI 会计算它们包含的所有视图,无论该视图是在屏幕内或屏幕外,如果有少量的视图需要渲染,使用它们是非常合适的。

与静态渲染相对的是动态渲染,比如 Table、List 等,它们支持滑动,根据数据动态渲染视图。对于规模较大的数据,优先使用动态渲染,系统会对此作出优化,只计算和渲染屏幕可见区域的视图以节省性能。

view 默认自身尺寸

aspectRatio(_:contentMode:) 约束宽高比,aspectRatio 参数为 nil 时,设置 contentMode 分别为 fill 和 fit 时等同于 scaledToFill() 和 scaledToFit()

Color 默认 infinity

如果外层 infinity,内层使用 fixedSize 可自适应为自身尺寸

获取视图尺寸:preferenceKey

Device size classes

https://developer.apple.com/documentation/swiftui/labeledcontent/alignmentguide(_:computevalue:)-23rd2

ignoresafearea