使用 SwiftUI 观察 window 调整大小事件

Observe window resize event with SwiftUI

我目前有一个 LazyVGrid 设置:

struct NetworkGrid: View {
    var networks: [Network]
    let columns = [
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible())
        ]
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(networks) { network in
                    NetworkCard(network: network)
                }
            }
        }
    }
}

我想根据当前window大小设置网格列数,即

func windowDidResize(_ notification: Notification) {
    itemWidth = CGFloat(300)
    if window.width <= itemWidth {
        GridItem(.flexible()), GridItem(.flexible())
    } else if window.width <= itemWidth * 2 {
        GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())
    } else if window.width <= itemWidth * 3 {
        GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())
    }
    ...
}

我将如何使用 SwiftUI 实现这样的观察者?

监听 window 大小的 SwiftUI 等价物可能会使用 GeometryReader。在您的示例中,您可以读取大小并根据其宽度读数动态决定列:

struct NetworkGrid: View {
    var networks: [Network]
    
    func columnsForWidth(width: CGFloat) -> [GridItem] {
        print("Columns for width: \(width)")
        return Array(repeating: GridItem(.flexible()), count: Int(width) / 100)
    }
    
    var body: some View {
        GeometryReader { geometry in
            ScrollView {
                LazyVGrid(columns: columnsForWidth(width: geometry.size.width)) {
                    ForEach(networks) { network in
                        NetworkCard(network: network)
                    }
                }
            }
        }
    }
}

如果要在调整视图大小时更新 @State@ObservedObject 变量,可以使用 onAppear(perform:) to update the variables with the initial view size and onChange(of:perform:) 检测视图大小变化:

struct MyView: View {
  @State private var size: CGSize = .zero

  var body: some View {
    GeometryReader { geometry in
      ZStack {
        Text("Hello World")
      }.onAppear {
        size = geometry.size
      }.onChange(of: geometry.size) { newSize in
        size = newSize
      }
    }
  }
}