在 UIViewRepresentable SwiftUI 中设置自定义 UIView 框架 [英] Set custom UIView frame in UIViewRepresentable SwiftUI

查看:41
本文介绍了在 UIViewRepresentable SwiftUI 中设置自定义 UIView 框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 UIViewRepresentable 在 SwiftUI 中使用我的自定义 UIView,我希望我的 UIView 与我在 .frame() 中设置的大小相同,以便我可以像这样使用它:

I'm trying to use my custom UIView in SwiftUI using UIViewRepresentable and I want my UIView to have the same size as I set in .frame() so that I can use it like this:

MyViewRepresentable()
.frame(width: 400, height: 250, alignment: .center)

例如,我可以将框架设置为属性:

For example, I can set a frame as a property:

struct MyViewRepresentable: UIViewRepresentable {
    var frame: CGRect
    func makeUIView(context: Context) -> UIView {
        let myView = MyView(frame: frame)

        return view
    }
    func updateUIView(_ uiView: UIView, context: Context) {}
}

用法:

struct ContentView: View {
    var body: some View {
        MyViewRepresentable(frame: CGRect(x: 0, y: 0, width: 400, height: 250))
            .frame(width: 400, height: 250, alignment: .center)
    }
}

这不是一个解决方案,我想知道如何使它正确.

It is not a solution and I wonder how to make it right.

推荐答案

如果 MyView 具有正确的内部布局(仅取决于自己的边界),则不需要外部附加限制,即

If MyView has correct internal layout (which depends only on own bounds), then there is not needs in external additional limitation, ie

struct MyViewRepresentable: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        return MyView(frame: .zero)
    }
    func updateUIView(_ uiView: UIView, context: Context) {}
}

将在 400x250 帧以下精确调整大小

will be exactly sized below having 400x250 frame

struct ContentView: View {
    var body: some View {
        MyViewRepresentable()
            .frame(width: 400, height: 250, alignment: .center)
    }
}

如果不是,则内部 MyView 布局有缺陷.

if it is not then internal MyView layout has defects.

这篇关于在 UIViewRepresentable SwiftUI 中设置自定义 UIView 框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆