How do you call a method on a UIView from outside the UIViewRepresentable in SwiftUI?(如何在SwiftUI中从UIView可表示的外部调用UIView上的方法?)
本文介绍了如何在SwiftUI中从UIView可表示的外部调用UIView上的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够将对UIViewRespresentable(或者可能是Coordinator)上的方法的引用传递给父View。我想要做到这一点的唯一方法是在父View结构上创建一个带有类的字段,然后将其传递给子结构,子结构充当此行为的委托。但它似乎相当冗长。
这里的用例是能够从标准SwiftUIButton调用方法,该方法将缩放MKMapView中的当前位置,该位置隐藏在树中的UIViewRepresentable中。我不希望当前位置是Binding,因为我希望此操作是一次性的,并且不会经常反映在用户界面中。
tl;dr是否有让父级在SwiftUI中获得对子级的引用的标准方法,至少对于UIViewRepresentables?(我知道这在大多数情况下可能并不可取,主要与SwiftUI模式背道而驰)。
推荐答案
我自己也很努力,以下是使用Combine和PassthroughSubject的方法:
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上的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何在SwiftUI中从UIView可表示的外部调用UIView上的方法?
基础教程推荐
猜你喜欢
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
