这些都是代码。
SurveyQuestion类
class SurveyQuestion: ObservableObject {
@Published var text: String
init() {
print("Initialising now ...")
self.text = "HELLO"
changeText()
}
func changeText() {
print("Changing Text Now from \(text).. ")
if self.text == "HELLO"{
self.text = "BYE"
}
else{
self.text = "HELLO"
}
print("to \(self.text) \n")
}
}
SubView.swift
struct SubView: View {
@ObservedObject var someOtherClass = SurveyQuestion()
var body: some View {
Text("Text now is \(someOtherClass.text)")
}
}
ContentView.swift
struct ContentView: View {
@ObservedObject var someClass = SurveyQuestion()
var body: some View {
VStack{
Button(action: {
print("Changing Text Now !")
self.someClass.changeText()
}) {
Text("Change Text ")
}
Text("Text now is \(someClass.text)")
SubView()
}
}
}
每当我单击“ changeText”按钮时,它都会更改Text(“ Text now is(someClass.text)”)中的文本,而不是Subview()。它们都应使用相同的文本更改进行更新。 知道这里出了什么问题吗?
答案 0 :(得分:0)
您的df1 = df1[df1.columns.interseciton(['Date', 'Amount', 'Name'],sort= False)]
df2 = df2[df2.columns.interseciton(['Date', 'Amount', 'Name'],sort= False)]
df3 = df3[df3.columns.interseciton(['Date', 'Amount', 'Name'],sort= False)]
df4 = df4[df4.columns.interseciton(['Date', 'Amount', 'Name'],sort= False)]
***Few line of code***
list_df = [df1, df2, df3, df4]
for df in list_df:
df = df.columns.to_series().map(col_fullform)
和someClass
是两个完全不同的对象。改变一个对另一个没有影响。如果假设这是一个可观察到的同时可以影响不同视图的情况,则您需要一个 environment 对象。
答案 1 :(得分:0)
要使其正常工作,您应该使用ObservableObject的相同实例,如下所示
struct SubView: View {
@ObservedObject var someOtherClass: SurveyQuestion // to be injected
var body: some View {
Text("Text now is \(someOtherClass.text)")
}
}
struct ContentView: View {
@ObservedObject var someClass = SurveyQuestion() // created
var body: some View {
VStack{
Button(action: {
print("Changing Text Now !")
self.someClass.changeText()
}) {
Text("Change Text ")
}
Text("Text now is \(someClass.text)")
SubView(someOtherClass: someClass) // << injected
}
}
}