SwiftUI:当 NSManagedObject(不是获取请求的一部分)bool 属性 更改时触发重绘?
SwiftUI: trigger redraw when NSManagedObject (not part of fetch request) bool property changes?
我在我的 SwiftUI 视图上安装了以下 @SectionedFetchRequest:
@SectionedFetchRequest(entity: Car.entity(),
sectionIdentifier: \.dealer.name,
sortDescriptors: [
NSSortDescriptor(key: "\(#keyPath(Car.dealer.name))", ascending: true),
NSSortDescriptor(key: "\(#keyPath(Car.milage))", ascending: true),
]
, predicate: nil,
animation: .default)
var carsResult: SectionedFetchResults<String, Car>
在视图中,我有这个:
LazyVStack {
ForEach(carsResult) { section in
if let dealer = section.first?.dealer {
Section(header: DealerSHView(dealer: dealer)) {
if dealer.isOpen {
ForEach(section) { channel in
....
}
} else {
....
}
}
}
}
}
当在 DealerSHView
上按下按钮时,dealer.isOpen 布尔值被切换。
Dealer
是一个 NSManagedObject,就像 Car
一样。
问题:
视图不更新,特别是这部分:
if dealer.isOpen {
ForEach(section) { channel in
....
}
} else {
....
}
没有效果,它只运行在第一次渲染时检测到的情况,但在 isOpen
更改时不运行,它通过核心数据保存保存到磁盘。
问题:
当 isOpen
发生变化时,如何让视图做出反应并重绘?
将其全部移动到 sub-View 中并像这样使用 @ObservedObject
:
struct DealerSection : View {
@ObservedObject var dealer: Dealer // body will be called when dealer changes.
var body: some View {
Section(header: DealerSHView(dealer: dealer)) {
if dealer.isOpen {
ForEach(section) { channel in
....
}
} else {
....
}
}
}
那么在你父视图的正文中它只是:
ForEach(carsResult) { section in
if let dealer = section.first?.dealer {
DealerSection(dealer: dealer)
}
}
我在我的 SwiftUI 视图上安装了以下 @SectionedFetchRequest:
@SectionedFetchRequest(entity: Car.entity(),
sectionIdentifier: \.dealer.name,
sortDescriptors: [
NSSortDescriptor(key: "\(#keyPath(Car.dealer.name))", ascending: true),
NSSortDescriptor(key: "\(#keyPath(Car.milage))", ascending: true),
]
, predicate: nil,
animation: .default)
var carsResult: SectionedFetchResults<String, Car>
在视图中,我有这个:
LazyVStack {
ForEach(carsResult) { section in
if let dealer = section.first?.dealer {
Section(header: DealerSHView(dealer: dealer)) {
if dealer.isOpen {
ForEach(section) { channel in
....
}
} else {
....
}
}
}
}
}
当在 DealerSHView
上按下按钮时,dealer.isOpen 布尔值被切换。
Dealer
是一个 NSManagedObject,就像 Car
一样。
问题: 视图不更新,特别是这部分:
if dealer.isOpen {
ForEach(section) { channel in
....
}
} else {
....
}
没有效果,它只运行在第一次渲染时检测到的情况,但在 isOpen
更改时不运行,它通过核心数据保存保存到磁盘。
问题:
当 isOpen
发生变化时,如何让视图做出反应并重绘?
将其全部移动到 sub-View 中并像这样使用 @ObservedObject
:
struct DealerSection : View {
@ObservedObject var dealer: Dealer // body will be called when dealer changes.
var body: some View {
Section(header: DealerSHView(dealer: dealer)) {
if dealer.isOpen {
ForEach(section) { channel in
....
}
} else {
....
}
}
}
那么在你父视图的正文中它只是:
ForEach(carsResult) { section in
if let dealer = section.first?.dealer {
DealerSection(dealer: dealer)
}
}