从SwiftUI按钮动作向UIView函数发送tapAction [英] Send tapAction from SwiftUI button action to UIView function
问题描述
我试图找到一种方法来触发在swiftUI
中点击按钮时将调用UIView
中的函数的动作.
I'm trying to find a way to trigger an action that will call a function in my UIView
when a button gets tapped inside swiftUI
.
这是我的设置:
Here's my setup:
当Button(SwiftUI)
被点击时
foo()(UIView)
需要运行
foo()(UIView)
needs to run when Button(SwiftUI)
gets tapped
class SomeView: UIView {
func foo() {}
}
要在swiftUI中使用我的UIView,必须将其包装在UIViewRepresentable
中
To use my UIView inside swiftUI I have to wrap it in UIViewRepresentable
struct SomeViewRepresentable: UIViewRepresentable {
func makeUIView(context: Context) -> CaptureView {
SomeView()
}
func updateUIView(_ uiView: CaptureView, context: Context) {
}
}
托管我的UIView()的SwiftUI视图
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
)中,并在点击操作中调用其方法:
You can store an instance of your custom UIView
in your representable struct (SomeViewRepresentable
here) and call its methods on tap actions:
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()
}
}
您的视图主体将如下所示:
And your view body will look like this:
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()
方法中添加了打印件:
To test it I added a print to the foo()
method:
class SomeView: UIView {
func foo() {
print("foo called!")
}
}
现在点击按钮将触发foo()
并显示打印语句.
Now tapping on your button will trigger foo()
and the print statement will be shown.
这篇关于从SwiftUI按钮动作向UIView函数发送tapAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!