Max
Max

Reputation: 876

SwiftUI Toggle Cannot convert value of type 'Bool?' to expected argument type 'Binding<Bool>'

With SwiftUI, I'm trying to set the toggle value, but it talk me Cannot convert value of type 'Bool?' to expected argument type 'Binding<Bool>' I Get data from the server, and Decodable the json create my model get data is successful, but when I want to change the Toggle it's Get the error.

MY CODE:

    struct content: View {
        @ObservedObject var articles = Article()
    
        var body: some View{
            
            VStack{
                List{
                    ForEach(articles.article, id: \.id){article in
                        
                        NavigationLink(destination: DetailView()) {
                                
                                ListContent(article: article)
                    }      
                }
            
                }        
            }
         }
    }


struct ListContent: View {
    var article: Article
    
    var body: some View {
        HStack {
            VStack (alignment: .leading) {

              Toggle("", isOn: self.article.isActive)
                .onChange(of: self.article.isActive) { value in
                    print(value)
                }
                
            }
            .padding(.leading,10)
            
            Spacer(minLength: 0)
            
        }     
    }
}

I can't use self.article.isActive in my code I'm afraid I'm doing something wrong or maybe I don't get how the Toggle work with isOn.

Any help or explanation is welcome! Thank you.

Upvotes: 2

Views: 8237

Answers (1)

Artem Chernousov
Artem Chernousov

Reputation: 509

You need to pass Binding variable to the 'isOn' parameter of the Toggle. I assume, that your 'isActive' variable of 'Article' has the Bool type.

        Toggle(model.title, isOn: Binding<Bool>(
                get: { model.isActive },
                set: {
                        // $0 is the new Bool value of the toggle
                        // Your code for updating the model, or whatever
                        print("value: \($0)")
                    }
        )

Example of the model, just in case

struct ToggleModel: Hashable {
    init(id: Int, title: String, isActive: Bool) {
        self.id = id
        self.title = title
        self.isActive = isActive
    }

    let id: Int
    let title: String
    let isActive: Bool
}

You can find working code example here: https://github.com/yellow-cap/toggle-list-swiftui/blob/master/SwiftUIToggleListExample/SwiftUIToggleListExample/ContentView.swift

Upvotes: 6

Related Questions