简体   繁体   中英

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

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() {....}

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)
        }
    }
        
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM