不能在同一视图中多次使用基于 UIView 的 UIViewRepresentable

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

当我尝试将多个 UIViewRepresentable 视图放置到 ContentView 时,它只显示最后一个。这是代码:

struct ContentView: View {
        
    @State var customView = UIView()
    
    var body: some View {
        NavigationView {
            VStack {
                CustomView(view: customView)
                
                CustomView(view: customView)
                    .offset(x: 100, y: 0)
            }
            .navigationTitle("Test UIViewRepresentable")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        makeNewView()
                    } label: {
                        Image(systemName: "plus")
                    }
                }
            }
        }
    }
    private func makeNewView() {
        let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 50, height: 50))
        let layer = CAShapeLayer()
        layer.path = path.cgPath
        layer.fillColor = CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
        customView.layer.addSublayer(layer)
    }
}

我在这里删除了模型和视图模型以简化代码。 这是可表示的 UIView:

struct CustomView: UIViewRepresentable {
    
    var view: UIView
    
    func makeUIView(context: Context) -> UIView {
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {}
}

第二个视图向下移动,因此第一个视图就位但未显示。我应该怎么做才能让两个视图都显示在 ContentView 中?

不是在 ContentView 中创建 @State var customView = UIView(),而是在 CustomView 中创建这个,然后像这样在 ContentView 中多次使用

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 视图

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