Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

You should bound Toggle to ObservedObject wrapper, like

struct ListContent: View {
    @ObservedObject var article: Article        // << here !!
    
    var body: some View {
        HStack {
            VStack (alignment: .leading) {

              Toggle("", isOn: $article.isActive)         // << binding !!
                .onChange(of: article.isActive) { value in
                    print(value)
                }

// ... other code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...