我有一个应用程序,一旦导航到第二页并显示一些结果,用户可以选择运行相同的功能但使用一些不同的参数。
我一直在想办法如何从第二个屏幕中运行我的初始屏幕中的函数......
我尝试了几种方法,但似乎陷入困境。我也尝试将 func 移至我的
@main
结构并使其成为全局的。似乎存在一些链接问题,因为我做错了。我已经将 ContentView.doFunction()
作为我需要运行 func 的示例,这显然不起作用,而且有点Pythonic..
我将提供非常基本的代码复制品。
struct ContentView: View {
@State private var readyToNavigate: Bool = false
var body: some View {
NavigationStack {
VStack {
Button(action: doFunction, label: {
Text("Button")
})
.navigationDestination(isPresented: $readyToNavigate) {
secondPage()}
.navigationTitle("Test")
}
}
}
func doFunction() {
Task {
let example = await "This is running an async operation"
print(example)
}
readyToNavigate = true
}
}
#Preview {
ContentView()
}
从另一个视图来看,它位于单独的 swift 文件中......
struct secondPage: View {
var body: some View {
Button("run func from first page", action: {
// ContentView.doFunction()
print("running async func from ContentView")
})
}
}
#Preview {
secondPage()
}
ContentView.doFunction
正在调用 ContentView 中的静态函数,而不是单个实例本身。当然,这是行不通的。
如果您希望多个视图共享相同的功能,您可能会考虑一种
ViewModel
,传递。
class ViewModel: ObservableObject {
@Published var readyToNavigate = false
func doFunction() {
//I don't know why you put await without any async task here. Just remove it.
let example = "This is running an async operation"
print(example)
readyToNavigate = true
}
}
那么在你看来:
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
NavigationStack {
VStack {
Button {
viewModel.doFunction()
} label: {
Text("Button")
}
.navigationDestination(isPresented: $viewModel.readyToNavigate) {
SecondPage(viewModel: viewModel)}
.navigationTitle("Test")
}
}
}
}
struct SecondPage: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
Button("run func from first page", action: {
viewModel.doFunction()
print("running async func from ContentView")
})
}
}