swiftui - 让 SwiftUI Picker() 选择更新应用程序状态更改的最佳方法是什么?
问题描述
我正在尝试使用 SwiftUI 制作一个 UI,其中列出了可以是不同种类并且可以更新的东西的集合。我想使用 Picker 在 UI 中设置类型,并且我还希望在以其他方式修改项目时更新视图(例如,从 UI 的另一部分或通过网络)。
我喜欢“redux”风格的设置,我不想放弃它。
这是一个简单的示例,它显示了两个项目,每个项目都有一个“随机化”按钮,可以随机更改项目,还有一个 Picker,可以让您选择新的项目类型。后者按预期工作:Picker
更改@State var
,商店更新等。“随机化”按钮更新商店和let
属性标签,但@State
和Picker
不更新。
我很想得到一些关于让这个以我想要的方式工作的好方法的建议。
import SwiftUI
import Combine
@main
struct PuffedWastApp: App {
var store = Store()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(store)
}
}
}
enum ItemState:String, CaseIterable {
case apple
case bannana
case coconut
}
enum Action {
case set(Int,ItemState)
}
class Store: ObservableObject {
@Published var state:[ItemState] = [.apple, .apple]
func reduce(_ action:Action) {
print("do an action")
switch (action) {
case let .set(index,new_state):
print("set \(index) to \(new_state)")
state[index] = new_state
self.objectWillChange.send()
}
}
}
struct ContentView: View {
@EnvironmentObject var store: Store
var body: some View {
VStack {
ForEach(store.state.indices) { index in
ItemContainer(index: index)
//Text("\(index)")
}
}
.padding()
}
}
struct ItemContainer: View {
@EnvironmentObject var store: Store
let index: Int
var body: some View {
ItemView(
index: index,
label: store.state[index], // let property: updates on change in the Store
localLabel: store.state[index], //@State variable; doesn't update on change in the Store
dispatch: store.reduce
)
.padding()
}
}
struct ItemView: View {
let index: Int
let label: ItemState
@State var localLabel: ItemState
let dispatch: (Action)->()
var body: some View {
HStack{
//Text("\(index)")
Text(label.rawValue)
Text(localLabel.rawValue)
Button("Randomize") { dispatch( .set(index, ItemState.allCases.randomElement() ?? .apple ) ) }
Picker("Item type", selection: $localLabel ) {
ForEach( ItemState.allCases , id: \.self ) {
Text($0.rawValue).tag($0)
}
}.onChange(of: localLabel) { dispatch(.set(index, $0)) }
}
.padding()
}
}
解决方案
尝试更改此行:
@State var localLabel: ItemState
至
@Binding var localLabel: ItemState
ItemView
并在你的初始化中传递它:
ItemView(
index: index,
label: store.state[index],
localLabel: $store.state[index],
dispatch: store.reduce
)
推荐阅读
- azure - 将 Visual Studio Professional 订阅添加到 Azure 帐户
- r - pdf_book 参考的页码是最终参考页,而不是第一页
- javascript - 概括为矩形的所有四个边找到最小尺寸的解决方案
- github - 受保护的分支设置中的检查列表中缺少 Github 操作状态检查
- python - 从数据框中删除列内的此字符串“\r”
- python - URL 中的 Web 脚本无效语法
- javascript - Angular:如何解决 - 阻止创建 WebMediaPlayer 的尝试,因为已经存在太多 WebMediaPlayer
- gnu - bash bc 命令将大写字母转换为 9
- javascript - 如何添加掷骰结果的总数?
- nestjs - 当我运行命令时,TypeORM 正在复制我的帖子 | CQRS