drago
drago

Reputation: 1303

How to pass Binding variable to an ObservableObject?

I have a binding variable that I need to pass to an ObservableObject in swiftUI.

Let's say I have this code:

struct MYView: View {

    @ObservedObject var fetch = Fetch()
    
    @Binding var IDTxt: Int
      
    var body: some View{
    
    //some code here

    }

}

Now I want to pass the IDTxt value to this:

public class Fetch: ObservableObject {

   
   //I need to pass the Binding variable here. something like this?
   @Binding var IDTxt: Int
    
    init(){
        load()
    }
    
    func load() {

    //So I can use it here like this:

    let url = URL(string: "http://someurl.com/\(IDTxt)")

    }

Could someone please advice on the above?

Upvotes: 2

Views: 2592

Answers (2)

David Pasztor
David Pasztor

Reputation: 54755

There's no need for Bindings if the property you are trying to inject into Fetch is coming from a parent view. You can simply inject the value in the init.

Also, if you are creating an ObservableObject inside a View, you need to declare it as @StateObject. @ObservedObject should only be used when injecting the object into the view.

public class Fetch: ObservableObject {
    
    init(id: Int) {
        load(id: id)
    }
    
    func load(id: Int) {
        let url = URL(string: "http://someurl.com/\(id)")

    }


struct MYView: View {

    @StateObject private var fetch: Fetch

    init(id: Int) {
        self._fetch = StateObject(wrappedValue: Fetch(id: id))
    }
      
    var body: some View{
        EmptyView()
    }

}

Upvotes: 2

Raja Kishan
Raja Kishan

Reputation: 19014

You do not need to pass the Binding value. But you can pass direct value.

public class Fetch: ObservableObject {
    
    var IDTxt: Int
    
    init(id: Int){
        self.IDTxt = id
        load()
    }
    
    func load() {
        
        //So I can use it here like this:
        
        let url = URL(string: "http://someurl.com/\(IDTxt)")
        
    }
}

struct MYView: View {
    
    @ObservedObject var fetch: Fetch
    
    @Binding var IDTxt: Int
    
    init(IDTxt: Binding<Int>) {
        self._IDTxt = IDTxt
        self.fetch = Fetch(id: IDTxt.wrappedValue)
    }
    
    var body: some View{
        
        //some code here
        Color.red
        
    }
}

If you want to observe IDTxt text then use @Published in class.

public class Fetch: ObservableObject {
    
    @Published var IDTxt: Int

Upvotes: 2

Related Questions