ios - 将 tapAction 从 SwiftUI 按钮操作发送到 UIView 函数

标签 ios swift swiftui

我正在尝试找到一种方法来触发一个操作,当在 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/

相关文章:

ios - 防止 UIScrollView 的 UIPanGestureRecognizer 阻塞 UIScreenEdgePanGestureRecognizer

ios - 如何在swift中正确读取ble外设值?

swift - 在 ZStack 中对齐对象

SwiftUI:删除行时使用 Array/Index 的 ForEach 崩溃

objective-c - 恢复上一个 View 及其 subview

ios - 链接 UIAlertAction 打开另一个 ViewController

swift - UIScrollView 内容插入由子树外部 View 的高度定义

ios - macOS 上的 SwiftUI 嵌套 ScrollView 问题

swift - 在沙盒 macOS 应用程序中访问苹果菜单时记录错误

ios - 在 Swift dequeueReusableCellWithIdentifier 中,需要时间来加载