【问题标题】:Cannot assign through subscript / environment key无法通过下标/环境键分配
【发布时间】:2021-04-27 13:57:08
【问题描述】:

在使用 SwiftUI 开发 iOS 应用程序时,我面临以下情况。根据我在网上的一些教程中找到的内容,我设置了一个自定义环境密钥。这是 SceneDelegate.swift 文件中的相关代码。

    .....
    private struct RowColorMaster: EnvironmentKey {
        static let defaultValue:[[String:Color]] = [[:]]
    }

    extension EnvironmentValues {
        var rowColorMasterDico:[[String:Color]] {
            get {self[RowColorMaster.self]}
            set {self[RowColorMaster.self] = newValue}
        }
    }
    .....
    var rowColorMasterDico:[[String:Color]]
    // Initialize rowColorMasterDico:
    rowColorMasterDico = ......
    .....
    let contentView = ContentView(.....)
                            .environment(\.managedObjectContext, context)
                            .environment(\.rowColorMasterDico, rowColorMasterDico)
    .....

然后在某个文件中进一步向下查看层次结构:

    .....
    @Environment(\.rowColorMasterDico) var rowColorMasterDico
    .....

    func handleEvent(_ file: String, flag: Bool) {
        rowColorMasterDico[page.index][file] = flag ? Color.red : Color.white
    }

一开始一切似乎都很顺利,直到我执行了 handleEvent 函数并收到此错误消息:

    Cannot assign through subscript: 'rowColorMasterDico' is a get-only property

我可以在我的代码中修改什么(可能是我的自定义环境键的设置方式)以便能够通过下标进行分配吗?

【问题讨论】:

    标签: ios swift swiftui swiftui-environment


    【解决方案1】:

    使您的环境对象可绑定。 这是可能的解决方案

    首先,进行绑定

    private struct RowColorMaster: EnvironmentKey {
        static var defaultValue: Binding<[[String:Color]]> = .constant([[:]])
    }
    
    extension EnvironmentValues {
        var rowColorMasterDico: Binding<[[String:Color]]> {
            get {self[RowColorMaster.self]}
            set {self[RowColorMaster.self] = newValue}
        }
    }
    

    接下来,在你的父视图中创建一个状态变量

    @State private var rowColorMasterDico:[[String:Color]] = []
    
    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(\.rowColorMasterDico, $rowColorMasterDico)
        }
    }
    

    现在,在子视图中

    @Environment(\.rowColorMasterDico) var rowColorMasterDico
    
    func handleEvent(_ file: String, flag: Bool) {
        rowColorMasterDico.wrappedValue[page.index][file] = flag ? Color.red : Color.white
    }
    

    【讨论】:

    • 谢谢,我试着按照你的想法去做。在修复了一些细节之后,我认为你的提示让我走上了正确的道路。但它还没有完全起作用。我在这里发了另一个(更新的)帖子:stackoverflow.com/questions/67314204/….
    • 在考虑使环境对象可绑定的想法之后。我做了一个新项目只是为了测试这个想法,但据我所知它不起作用。
    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2021-09-29
    • 2020-04-08
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多