为什么 swiftui 不能区分 2 个不同的环境对象? [英] Why can't swiftui distinguish 2 different environment objects?

查看:30
本文介绍了为什么 swiftui 不能区分 2 个不同的环境对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码并且希望 b 作为文本.

I have this code and would expected a b as Text.

结果:a -> 看截图.我做错了什么?

Result: a a -> see screenshot. What am I doing wrong?

import SwiftUI

class PublishString : ObservableObject {

    init(string: String) {
        self.string = string
        print(self.string)
    }

    @Published var string : String = "a"
}

struct ContentView: View {

    @EnvironmentObject var text1 : PublishString
    @EnvironmentObject var text2 : PublishString

    var body: some View {
        VStack {
            Text(text1.string)
            Text(text2.string)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(PublishString(string: "a"))
        .environmentObject(PublishString(string: "b"))
    }
}

和...这有效:

class PublishString : ObservableObject {

    init(string: String) {
        self.string = string
        print(self.string)
    }

    @Published var string : String = "a"
}

class PublishString2 : ObservableObject {

    init(string: String) {
        self.string = string
        print(self.string)
    }

    @Published var string : String = "a"
}

struct ContentView: View {

    @EnvironmentObject var text1 : PublishString
    @EnvironmentObject var text2 : PublishString2

    var body: some View {
        VStack {
            Text(text1.string)
            Text(text2.string)
        }
    }
}

推荐答案

正如 Asperi 在评论中所指出的,SwiftUI通过类型(您使用的类定义)标识环境对象.它查找该类型的对象并使用它找到的第一个对象.

As noted by Asperi in the comment, SwiftUI identifies Environment Objects by the type (the class definition you have used). It looks for an object of that type and uses the first one it finds.

一种选择是在您可以访问的一个对象上拥有多个属性(这意味着在您的情况下有两个单独的 String 属性.

One option is to have multiple properties on the one object that you can access (this would mean two separate String properties in your case.

在 Apple 文档上提供了更多信息.

Further information is available on the Apple documentation.

这篇关于为什么 swiftui 不能区分 2 个不同的环境对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆