SwiftUI 的布局系统让我们在设计响应式和动态布局时更加便捷。基础的布局已经在第二章讲述过来,所以这一章,我们将深入布局系统,介绍如何在复杂场景中运用 SwiftUI 的布局能力,包括利用 GeometryReader 实现自适应布局,探讨高级容器 LazyVGrid 和 LazyHGrid 的实际应用,以及如何创建自定义布局容器。
6.1 利用 GeometryReader 实现自适应布局
在复杂的界面布局中,我们经常需要根据设备尺寸调整界面结构,而 GeometryReader 为我们提供了获取父视图尺寸的能力。通过 GeometryReader,可以在小屏幕设备上创建单列布局,而在大屏幕上自动适配多列布局。
示例:自适应网格布局
struct AdaptiveGrid: View {
let items = Array(1...50)
var body: some View {
GeometryReader {
geometry in
let columns = geometry.size.width > 600 ? 4 : 2
LazyVGrid(columns: Array(repeating: .init(.flexible()), count: columns)) {
ForEach(items, id: \.self) {
item in
Text("Item \(item)")
.frame(width: geometry.size.width / CGFloat(columns) - 10, height: 50)
.background(Color.blue.opacity(0.5

最低0.47元/天 解锁文章
970

被折叠的 条评论
为什么被折叠?



