我正在尝试设置一个环境变量,如下文档:https://developer.apple.com/documentation/swiftui/environmentvalues
这是我的代码--
App.swift:
@main
struct GiniAppsApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.environment(\.hits, [])
}
}
}
private struct HitsArrayKey: EnvironmentKey {
static let defaultValue: [Hit] = []
}
extension EnvironmentValues {
var hits : [Hit] {
get { self[HitsArrayKey.self] }
set { self[HitsArrayKey.self] = newValue }
}
}
extension View {
func myCustomValue(_ myCustomValue: [Hit]) -> some View {
environment(\.hits, myCustomValue)
}
}
但是当我试图在视图中更改\更新变量时,我得到错误-
- 〉无法分配给属性:'hits'是一个只获取属性 *
下面是视图的代码:
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@Environment(\.hits) private var hits: [Hit]
var body: some View {
Button(action: addItem) {
Label("GET", systemImage: "plus")
hits = [] //ERROR: Cannot assign to property: 'hits' is a get-only property
}
...
1条答案
按热度按时间gk7wooem1#
通常,更改环境变量值的方法如下:
因为你有一个自定义的修饰符,你也可以使用