I found this question SwiftUI: Putting multiple BindableObjects into Envionment
the answer said environmentObject(ObservableObject) returns modified view, therefore I can make call chain for multiple environmentObject.
like
let rootView = ContentView()
.environmentObject(firstBindable)
.environmentObject(secondBindable)
and I wonder what is result if firstBindable and secondBindable are same type. how .environmentObject()
knows what is exect value which is a programmer intended to set between firstBindable
and secondBindable
.
so I tested this
- I made an ObservableObject class
final class TempStr: ObservableObject {
@Published var tmpStr = "temp"
init(initStr: String) {
tmpStr = initStr
}
}
- made call chain of environmentObject from sceneDelegate
window.rootViewController
= UIHostingController(rootView:
TestView()
.environmentObject(TempStr(initStr: "1st"))
.environmentObject(TempStr(initStr: "2nd"))
- and used values from View
struct TestView: View {
@EnvironmentObject var tmp1: TempStr
@EnvironmentObject var tmp2: TempStr
var body: some View {
Text(tmp1.tmpStr + " " + tmp2.tmpStr)
}
}
- result was '1st 1st'
And if my code calls one .environmentObject() like
TestView().environmentObject(TempStr(initStr: "1st"))
both tmp1 and tmp2 from TestView have same value TempStr(initStr: "1st")
. it looks like .environmentObject()
call sets all values of same type.
Actually, I knew that it couldn't work but I just tried it for using this question.
I wonder what is correct way of achieving my goal.
Thanks