Send tapAction from SwiftUI button action to UIView function

后端 未结 2 1539
情歌与酒
情歌与酒 2020-12-20 14:38

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.

2条回答
  •  隐瞒了意图╮
    2020-12-20 15:27

    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")
            }
          }
        }
      }
    

    To test it I added a print to the foo() method:

    class SomeView: UIView {
    
      func foo() {
        print("foo called!")
      }
    }
    

    Now tapping on your button will trigger foo() and the print statement will be shown.

提交回复
热议问题