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")
}
}
}
}
}
}
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
How to Add a Show More/Show Less Uibutton to Control Uitextview
Integrate Existing Aws Cognito User Pool into iOS Project with Amplify
iOS Corebluetooth: Startadvertising() Error Advertising Static Data
Checking User Location Permission Status on iOS 14
C-Style Uninitialized Pointer Passing in Apple Swift
How to Cast Up to Super Class When There Is an Override Function in the Sub Class
How to Add an Uicollectionviewlayout Programmatically
Saving Coredata to a Web Server with Swift 3.0
Swift Firebase Using an Unspecified Index
Convert String to Staticstring
Toggle Sidebar in Swiftui Navigationview on MACos
Closure:Use Unresolved Identifier 'Self'
How to Import Googleanalytics Header into a Library Framework
In Swift, Why Can't I Instantiate a Protocol When It Has an Initialiser