问题描述
我正在尝试找到一种方法来触发一个操作,当一个按钮在 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
.
这是我的设置:
foo()(UIView)
需要在 Button(SwiftUI)
被点击时运行
foo()(UIView)
needs to run when Button(SwiftUI)
gets tapped
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 视图
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 按钮动作中的 tapAction 发送到 UIView 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!