• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SwiftUI 按钮动作的 tapAction 发送到 UIView 函数

用户头像
it1352
帮助1

问题说明

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

正确答案

#1

您可以将自定义 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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcffcec
系列文章
更多 icon
同类精品
更多 icon
继续加载