在ObservableObject中导入变量

时间:2019-11-11 16:49:34

标签: ios swift xcode swiftui

我想在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
    }
 }

非常感谢。

1 个答案:

答案 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
   }
}

请参阅:https://www.hackingwithswift.com/quick-start/swiftui/observable-objects-environment-objects-and-published