如何解决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)
和 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。