gpt4 book ai didi

ios - 从 SwiftUI View 调用本地 UIViewController 函数

转载 作者:行者123 更新时间:2023-11-28 07:20:12 25 4
gpt4 key购买 nike

我正在尝试从 ContentView 调用本地 ViewController 函数。该函数使用了一些局部变量,不能移到 ViewController 之外。

class ViewController: UIViewController {
func doSomething() {...}
}

extension ViewController : LinkViewDelegate {...}

位于不同的文件中:

struct ContentView: View {

init() {
viewController = .init(nibName:nil, bundle:nil)
}
var viewController: viewController

var body: some View {
Button(action: {self.viewController.doSomething()}) {
Text("Link Account")
}
}
}

UIViewController 不能更改为类似 UIViewRepresentable 的东西,因为 LinkViewDelegate 只能扩展 UIViewController。

最佳答案

因此您需要在 SwiftUI 中创建一个简单的 bool 绑定(bind),将其翻转为 true 以触发 UIKit viewController 中的函数调用,然后将其设置回 false 直到下一次按下 swiftUI 按钮。 (至于 LinkViewDelegate 阻止像 UIViewControllerRepresentable 这样不应阻止您的事情,请使用 Coordinator 来处理委托(delegate)调用。)

struct ContentView: View {

@State var willCallFunc = false

var body: some View {
ViewControllerView(isCallingFunc: $willCallFunc)

Button("buttonTitle") {
self.willCallFunc = true
}
}
}

struct ViewControllerView: UIViewControllerRepresentable {

@Binding var isCallingFunc: Bool

func makeUIViewController(context: Context) -> YourViewController {
makeViewController(context: context) //instantiate vc etc.
}

func updateUIViewController(_ uiViewController: YourViewController, context: Context) {
if isCallingFunc {
uiViewController.doSomething()
isCallingFunc = false
}
}
}

关于ios - 从 SwiftUI View 调用本地 UIViewController 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com