SwiftUI框架大小

11

如何在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))
    }
    ....
}

苹果官方教程经常使用.zero,但在这种情况下无效。


1
makeUIView 返回一个 .zero 帧,并尝试在 UIViewRepresentableupdateUIView 方法中触发绘制。 - Matteo Pacini
2个回答

6
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)
    }
    ....
}

4

在创建UIView时,框架大小并不重要(即在makeUIView中),因为构建的视图将根据容器视图中的最终布局进行调整大小,并且结果框架将通过UIView.draw传递。

以下是完整的示例(Xcode 11.1)和预览(注意:如果您从下面的VStack中删除,则DrawView将填充整个屏幕)。

Drawing in UIViewRepresentable

import SwiftUI
import UIKit

class DrawView : UIView {
    override func draw(_ rect: CGRect) {
        let path = UIBezierPath(ovalIn: rect)
        UIColor.green.setFill()
        path.fill()
    }
}

struct SwiftDrawView: UIViewRepresentable {
    typealias UIViewType = DrawView

    func makeUIView(context: Context) -> DrawView {
        DrawView()
    }

    func updateUIView(_ uiView: DrawView, context: UIViewRepresentableContext<SwiftDrawView>) {
        // change here some DrawView properties if needed, eg. color
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            SwiftDrawView()
            Text("SwiftUI native")
        }
            .edgesIgnoringSafeArea(.all)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接