宋明

  • 2024
  • 2023
  • 2022

2024 年发布 107 篇

2023 年发布 25 篇

2022 年发布 25 篇

3.9 自定义布局(Layout)



SwiftUI 内置了丰富的布局容器,也支持简单的布局调整,它们能够解决大多数常用的布局需求。但仍然有所限制,比如 HStack 或者 VStack,它们只能在单一线性轴上进行布局,Grid 虽然可以兼顾横向和纵向,但子视图的位置不能随意调整。

而 Layout 协议支持自定义布局,我们可以使用它随心所欲地实现各种纷繁的布局效果。

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