ios - SwiftUI - 如何使用 Firebase 中的字符串从另一个视图更新 @state 变量?
问题描述
所以我的问题是我想从来自 Firebase的不同视图中的名称(不是绑定变量而是字符串)更改主视图中的国家/地区名称?
所以这是我的主要内容ContentView
:
struct ContentView: View {
@State var showModal: Bool = false
@State var country: String = "Netherlands"
var body: some View {
VStack {
Button(action: {
// ...
}) {
RaceView(showModal: $showModal, country: country)
}.sheet(isPresented: $showModal) {
RaceModalView(showModal: self.$showModal, country: self.$country)
}
}
}
}
它显示RaceView
为按钮,单击时RaceModalView
将显示为(工作表)模式。
在RaceModalView
它显示了多个RaceView
基于来自 Firebase 的数据的列表。这是RaceModalView
:
struct RaceModalView: View {
@ObservedObject var viewModel = RacesViewModel()
@Binding var showModal: Bool
@Binding var country: String
var body: some View {
NavigationView {
List(viewModel.races){ race in
RaceView(showModal: self.$showModal, country: race.country)
}
}.onAppear {
self.viewModel.fetchData()
}
}
}
在RaceView
其将国家名称显示为切换实际模式(上图)的按钮时。这是RaceView
:
struct RaceView: View {
@Binding var showModal: Bool
var country: String
var body: some View {
Button(action: {
self.showModal.toggle()
}) {
Text(country)
}
}
}
所以我country
在这个中使用了一个正常的变量RaceView
。但是当我将其更改为绑定变量时,它会引发错误:
Cannot convert value of type 'String' to expected argument type 'Binding<String>'
因为在创建列表的 RaceModalView 中,它传递了一个字符串而不是预期的绑定。但这country: race.country
是来自 Firebase 作为字符串。我无法将其更改为race.$country
.
我怎样才能更新@State var country
主要ContentView
?
解决方案
此解决方案使用操作来更新绑定。
RaceModalView.swift
struct RaceModalView: View {
@ObservedObject var viewModel = RacesViewModel()
@Binding var showModal: Bool
@Binding var country: String
var body: some View {
NavigationView {
List(viewModel.races){ race in
RaceView(showModal: self.$showModal, country: race.country) {
self.country = race.country
}
}
}.onAppear {
self.viewModel.fetchData()
}
}
}
RaceView.swift
struct RaceView: View {
@Binding var showModal: Bool
var country: String
var action: () -> () = {}
var body: some View {
Button(action: {
self.action()
self.showModal.toggle()
}) {
Text(country)
}
}
}
推荐阅读
- amazon-web-services - 就像 AWS Fargate 任务一样,在 Azure 上使用相同的 docker 映像运行多个容器实例
- java - h2 中的 onetoone 关系不会为一侧生成 id
- javascript - 我可以更改grapesjs中的工具栏语言吗?
- angular - Stencil 调用 Ionic Angular 子组件函数或生命周期钩子
- python - pyparsing:根据条件使用字符
- html - 如何更改各种 HTML 元素的强调色
- duplicates - 防止 Moodle 嵌入式答案中的重复(完形填空)
- java - Spring从GET url查询中设置@PostMapping字段?
- c - 我该如何解决这个错误?切换语句
- java - SpringBootTest 服务测试 - MockitoAnnotations Giving NoSuchMethodError: openMocks (java.lang.AutoCloseable)