swiftui - SwiftUI - 如何正确重新加载 @ObservableObject 对象
问题描述
我已经开始将我的应用程序 [RsyncOSX][1] 重写为 SwiftUI(需要学习很多东西)。配置和时间表是从永久存储中读取的,这很好。以下代码完成了这项工作:
import SwiftUI
struct Readdatafromstore {
var profile: String?
var configurationData: ConfigurationsSwiftUI
var validhiddenIDs: Set<Int>
var scheduleData: SchedulesSwiftUI
init(profile: String?) {
self.profile = profile
self.configurationData = ConfigurationsSwiftUI(profile: self.profile)
self.validhiddenIDs = self.configurationData.getvalidhiddenIDs() ?? Set()
self.scheduleData = SchedulesSwiftUI(profile: self.profile, validhiddenIDs: self.validhiddenIDs)
}
}
final class RsyncOSXdata: ObservableObject {
@Published var rsyncdata: Readdatafromstore?
@Published var configurations: [Configuration]?
@Published var schedulesandlogs: [ConfigurationSchedule]?
@Published var arguments: [ArgumentsOneConfiguration]?
init(profile: String?) {
self.rsyncdata = Readdatafromstore(profile: profile)
self.configurations = self.rsyncdata?.configurationData.getconfigurations() ?? []
self.schedulesandlogs = self.rsyncdata?.scheduleData.getschedules() ?? []
self.arguments = self.rsyncdata?.configurationData.getarguments() ?? []
}
}
视图加载了以下内容:
let contentView = ContentView().environmentObject(RsyncOSXdata(profile: "profilename"))
视图通过以下方式读取数据
@EnvironmentObject private var rsyncOSXData: RsyncOSXdata
配置由配置文件存储,问题是:如何重新加载@ObservableObject?默认配置文件在开始时被读取和加载。
重新加载@ObservableObject
对象不会更新视图...
解决了
contentView 的调用发生了变化,调用侧边栏功能时设置了 environmentObject ..
let contentView = ContentView()
...
window.contentView = NSHostingView(rootView: contentView)
和内容视图():
struct ContentView: View {
@State private var selectedprofile: String?
var profiles: [String]? {
return Catalogsandfiles(profileorsshrootpath: .profileroot).getcatalogsasstringnames()
}
var body: some View {
VStack {
Picker("Profile: ", selection: $selectedprofile) {
ForEach(0 ..< (profiles?.count ?? 0)) {
Text(self.profiles?[$0] ?? "").tag(self.profiles?[$0])
}
}
SidebarNavigation().environmentObject(RsyncOSXdata(profile: selectedprofile))
Text(selectedprofile ?? "Default")
}
}
}
选择一个新的配置文件现在会自动更新视图,因为它们应该是。我现在不知道为什么更改解决了这个问题,但它有效.. [1]:https ://github.com/rsyncOSX/RsyncOSX
解决方案
推荐阅读
- c# - 我的 If-Statement 运行时没有得到所需的输入?
- css - 如何在 react-bootstrap 的选项卡中添加样式?
- python - 为什么有特定于 VSCode 终端的 conda 故障,而不是普通终端?
- python - 基于部分值 Python 创建类别
- android - 有什么办法可以防止 React Native IOS 0.63 版中的截图?
- python - JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in POST request
- lotus-notes - (LotusScript)notes文档按钮如何更新sql?
- java - 安卓 | 如何使用 Picasso 将一些图片加载到 SliderView 中?
- php - 正则表达式延迟捕获在懒惰的“任何东西”之后失败......除非我知道接下来会发生什么
- android - Android 一键登录:无法显示密码保存对话框