Set Custom Uiview Frame in Uiviewrepresentable Swiftui

Set custom UIView frame in UIViewRepresentable SwiftUI

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.

Can't use UIViewRepresentable based on UIView more than once in the same View

Instead of creating @State var customView = UIView() in ContentView create this in CustomView and use in ContentView Multiple Times like this

UIViewRepresentable

    struct CustomView: UIViewRepresentable {

var view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

func makeUIView(context: Context) -> UIView {
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 100, height: 100))
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
view.layer.addSublayer(layer)
return view
}

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

SwiftUI View

struct ContentView: View {

var body: some View {
NavigationView {
VStack {
CustomView()

CustomView()
.offset(x: 100, y: 0)
}
.navigationTitle("Test UIViewRepresentable")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
// CustomView()
} label: {
Image(systemName: "plus")
}
}
}
}

}

}

Sample Image

How to find the frame of a SwiftUI UIViewRepresentable

It is due to use of GeometryReader

Try to use

custonView(model:self.model)
.fixedSize()

UIViewRepresentable remains white

Remove this line after the super.init.

translatesAutoresizingMaskIntoConstraints = false


Related Topics



Leave a reply



Submit