(在 Xcode 11.3、Swift 5.1.3 中测试)
我想扩展 UIView,用 UIViewRepresentable 包装它,并将其用作 Swift View。但是,我很难从包装器 Swift View 访问自定义 UIView 的扩展功能。
class UICameraCaptureImageView: UIImageView, AVCaptureVideoDataOutputSampleBufferDelegate {
@State var capturedImage: UIImage? = UIImage(named: "default_placeholder")
func startCameraCapture() {
// start camera capture when it is ready
}
// AVCaptureVideoDataOutputSampleBufferDelegate delegate method follows
// ...
}
struct CameraCaptureImageView: UIViewRepresentable {
// cannot set containedUIView in makeUIView/updateUIView, and they are not mutating method
private var containedUIView: UICameraCaptureImageView?
func makeUIView(context: UIViewRepresentableContext<CameraCaptureImageView>) ->
UICapturedImageView {
UICapturedImageView()
}
func updateUIView(_ uiView: UICapturedImageView,
context: UIViewRepresentableContext< CameraCaptureImageView>) {
uiView.image = capturedImage
}
func startCameraCapture() {
// redirect to UICameraCaptureImageView.startCameraCapture(),
// but cannot set self.containedUIView
guard self.containedUIView != nil else {
print("The containedUICaptureView doesn't exist")
return
}
self.containedUIView?.startCameraCapture()
}
}
起初,虽然是一种有状态的策略,但我尝试在 CameraCaptureImageView 中声明一个成员变量,并在创建时设置 UICameraCaptureImageView 实例。但正如您所见,makeUIView() 并未声明为变异方法,因此我无法变异 CameraCaptureImageView 的任何成员。
如何从 UIViewRepresentable 包装器访问我的 UIView 子类中的扩展自定义函数 startCameraCapture()?或者,是否有任何无状态、体面的解决方案可以在 SwiftUI 中使用扩展的旧 UIView?