我想在ObservableObject中导入一个实际变量集:
我的代码是:
import SwiftUI
struct HomepageView: View {
@ObservedObject var obs = observer()
var myMainVar: Bool = true
var body: some View {
// My view here... does not matter
}
}
class observer : ObservableObject{
init() { // how to import my variable myMainVar inside my init ?
loadDataByAlamofire()
}
private func loadDataByAlamofire() { // how to import this variable in the private func?
var url = "blabla.xyz?boolean="+myMainVar
}
}
非常感谢。
答案 0 :(得分:0)
我会将myMainVar
放在观察者类中,以便可以在任何功能中使用它。然后,用@Published
标记变量,以便变量中的任何更改都会触发视图重新加载。最后,通过点语法obs.myMainVar
访问视图中的变量。
例如:
import SwiftUI
struct HomepageView: View {
@ObservedObject var obs = observer()
var body: some View {
// My view here... does not matter
// Display value of variable in text
Text("\(obs.myMainVar)")
}
}
class observer : ObservableObject{
@Published var myMainVar: Bool = true
init() { // how to import my variable myMainVar inside my init ?
loadDataByAlamofire()
}
private func loadDataByAlamofire() { // how to import this variable in the private func?
var url = "blabla.xyz?boolean="+myMainVar
}
}