Home > Software design >  How do I change the variable "url" which is inside of a class by using a struct? in swift
How do I change the variable "url" which is inside of a class by using a struct? in swift

Time:12-20

I'm new to swift and I cannot figure out how to change the url variable by inputting the Binding var url from the struct. I keep getting errors regardless of how I try it. Any help would v vvv appreciated

struct SearchView : View {
    
    @State var showSearchView = true
    @State var color = Color.black.opacity(0.7)
    **@Binding var url: String**
    @ObservedObject var Books = getData()
    
    var body: some View{
        

        if self.showSearchView
        {
            NavigationView{
                
                List(Books.data) {i in 
....}

class getData : ObservableObject{
    
    @Published var data = [Book]()
    **var url** = "https://www.googleapis.com/books/v1/volumes?q=harry potter"
    
    init() {....}

CodePudding user response:

First of all if the current view owns the model object use @StateObject.

Second of all please name classes with starting uppercase and functions and variables with starting lowercase letter.

@StateObject var books = GetData()

...

class GetData : ObservableObject {

You don't need a Binding just address the property directly

books.url = "https://apple.com"

and delete

@Binding var url: String


And if you need to display the changed value immediately use a @Published property and bind the it directly

class GetData : ObservableObject {

    @Published var url = "https://www.googleapis.com/books/v1/volumes?q=harry potter"

...


struct SearchView : View {
   
    @StateObject var books = GetData()
    
    var body: some View {
        
        VStack{
            Text(books.url)
            TextField("URL", text: $books.url)
        }
    }
        
}

CodePudding user response:

Change the *var url** = "https://www.googleapis.com/books/v1/volumes?q=harry potter" in the second view with: @State var url = "https://www.googleapis.com/books/v1/volumes?q=harry potter" so it can be mutable

  • Related