我正在尝试找到一种方法来触发一个操作,当在 swiftUI
中点击一个按钮时,该操作将在我的 UIView
中调用一个函数。
Here's my setup:
foo()(UIView)
需要在 Button(SwiftUI)
被点击时运行
我的自定义 UIView 类使用 AVFoundation 框架
class SomeView: UIView {
func foo() {}
}
要在 swiftUI 中使用我的 UIView,我必须将它包装在 UIViewRepresentable
struct SomeViewRepresentable: UIViewRepresentable {
func makeUIView(context: Context) -> CaptureView {
SomeView()
}
func updateUIView(_ uiView: CaptureView, context: Context) {
}
}
托管我的 UIView() 的 SwiftUI View
struct ContentView : View {
var body: some View {
VStack(alignment: .center, spacing: 24) {
SomeViewRepresentable()
.background(Color.gray)
HStack {
Button(action: {
print("SwiftUI: Button tapped")
// Call func in SomeView()
}) {
Text("Tap Here")
}
}
}
}
}
最佳答案
您可以将自定义 UIView
的实例存储在您的可表示结构中(此处为 SomeViewRepresentable
)并在点击操作时调用其方法:
struct SomeViewRepresentable: UIViewRepresentable {
let someView = SomeView() // add this instance
func makeUIView(context: Context) -> SomeView { // changed your CaptureView to SomeView to make it compile
someView
}
func updateUIView(_ uiView: SomeView, context: Context) {
}
func callFoo() {
someView.foo()
}
}
您的 View 主体将如下所示:
let someView = SomeViewRepresentable()
var body: some View {
VStack(alignment: .center, spacing: 24) {
someView
.background(Color.gray)
HStack {
Button(action: {
print("SwiftUI: Button tapped")
// Call func in SomeView()
self.someView.callFoo()
}) {
Text("Tap Here")
}
}
}
}
为了测试它,我在 foo()
方法中添加了打印:
class SomeView: UIView {
func foo() {
print("foo called!")
}
}
现在点击您的按钮将触发 foo()
并显示打印语句。
关于ios - 将 tapAction 从 SwiftUI 按钮操作发送到 UIView 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584059/