SwiftUI框架大小

Lim*_*ean 6 swift swiftui

如何在UIViewRepresentable中获得框架大小?

我有一个简单的DrawView类,它可以绘制一些东西,我想与SwiftUI集成。如果我将帧大小硬编码为640x480,则此代码有效,但是有可能知道ContentView的当前帧大小吗?

struct ContentView: View {
    var body: some View {
        SwiftDrawView()
    }
}

struct SwiftDrawView: UIViewRepresentable {
    func makeUIView(context: Context) -> DrawView {
        DrawView(frame:CGRect(x: 0, y: 0, width: 640, height: 480))
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

Apple教程始终使用.zero,在这种情况下将无法使用。

Vic*_*rov 5

struct ContentView: View {
    var body: some View {
        GeometryReader { proxy in
            SwiftDrawView(frame: proxy.frame(in: .local))
        }
    }
}

struct SwiftDrawView: UIViewRepresentable {
    let frame: CGRect

    func makeUIView(context: Context) -> DrawView {
        DrawView(frame:frame)
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)