首页 > 解决方案 > 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

标签: iosswiftui

解决方案


此解决方案使用操作来更新绑定。

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)
        }
    }
}

推荐阅读