如何在SwiftUI中从UIView可表示的外部调用UIView上的方法? [英] How do you call a method on a UIView from outside the UIViewRepresentable in SwiftUI?

查看:35
本文介绍了如何在SwiftUI中从UIView可表示的外部调用UIView上的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将对UIViewRespresentable(或者可能是Coordinator)上的方法的引用传递给父View。我想要做到这一点的唯一方法是在父View结构上创建一个带有类的字段,然后将其传递给子结构,子结构充当此行为的委托。但它似乎相当冗长。

这里的用例是能够从标准SwiftUIButton调用方法,该方法将缩放MKMapView中的当前位置,该位置隐藏在树中的UIViewRepresentable中。我不希望当前位置是Binding,因为我希望此操作是一次性的,并且不会经常反映在用户界面中。

tl;dr是否有让父级在SwiftUI中获得对子级的引用的标准方法,至少对于UIViewRepresentables?(我知道这在大多数情况下可能并不可取,主要与SwiftUI模式背道而驰)。

推荐答案

我自己也很努力,以下是使用CombinePassthroughSubject的方法:

struct OuterView: View {
  private var didChange = PassthroughSubject<String, Never>()

  var body: some View {
    VStack {
      // send the PassthroughSubject over
      Wrapper(didChange: didChange)
      Button(action: {
        self.didChange.send("customString")
      })
    }
  }
}

// This is representable struct that acts as the bridge between UIKit <> SwiftUI
struct Wrapper: UIViewRepresentable {
  var didChange: PassthroughSubject<String, Never>
  @State var cancellable: AnyCancellable? = nil

  func makeUIView(context: Context) → SomeView {
    let someView = SomeView()
    // ... perform some initializations here

    // doing it in `main` thread is required to avoid the state being modified during
    // a view update
    DispatchQueue.main.async {
      // very important to capture it as a variable, otherwise it'll be short lived.
      self.cancellable = didChange.sink { (value) in
        print("Received: (value)")
        
        // here you can do a switch case to know which method to call
        // on your UIKit class, example:
        if (value == "customString") {
          // call your function!
          someView.customFunction()
        }
      }
    }

    return someView
  }
}

// This is your usual UIKit View
class SomeView: UIView {
  func customFunction() {
    // ...
  }
}

这篇关于如何在SwiftUI中从UIView可表示的外部调用UIView上的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆