我有多个@AppStorage
Package 的变量:
@AppStorage(Keys.test1.rawValue) var test1 = false
@AppStorage(Keys.test2.rawValue) var test2 = 0
@AppStorage(Keys.test3.rawValue) var test3 = 1.0
// ... Many more
而且我想把它们都重置为默认值,而不需要一个接一个地重新设置。
我为UserDefaults添加了一个扩展以重置密钥:
enum Keys: String, CaseIterable {
case test1 = "TestKey1"
case test2 = "TestKey2"
case test3 = "TestKey3"
}
extension UserDefaults {
func resetKeys(){
Keys.allCases.forEach {
removeObject(forKey: $0.rawValue)
}
}
}
但在使用UserDefauls.standard.resetKeys()
重置后,它确实重置了,但根本没有更新SwiftUI视图,除非我关闭应用程序并重新启动。
具有手动执行此操作的功能,可立即更新视图:
func resetKeys() {
test1 = false
test2 = 0
test3 = 1.0
}
整个样品:
enum Keys: String, CaseIterable {
case test1 = "TestKey1"
case test2 = "TestKey2"
case test3 = "TestKey3"
}
class SomeClass: ObservableObject {
@AppStorage(Keys.test1.rawValue) var test1 = false
@AppStorage(Keys.test2.rawValue) var test2 = 0
@AppStorage(Keys.test3.rawValue) var test3 = 1.0
// ... Many more
}
struct ContentView: View {
@EnvironmentObject var storage: SomeClass
var body: some View {
...
}
}
extension UserDefaults {
func resetKeys(){
Keys.allCases.forEach {
removeObject(forKey: $0.rawValue)
}
}
}
1条答案
按热度按时间vxqlmq5t1#
Package 器符合
DynamicProperty
,需要它来通知View
有更改。使用
AppStorage
或在ObservableObject
中调用objectWillChange.send()
进行更改