swiftuikitswiftuiuiviewrepresentable

Set custom UIView frame in UIViewRepresentable SwiftUI


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) {}
}

Usage:

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.


Solution

  • 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) {}
    }
    

    will be exactly sized below having 400x250 frame

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

    if it is not then internal MyView layout has defects.