简体   繁体   中英

Binding variable in ForEach not update

I want to change the rating star's images when another Movie card is clicked. Other text information changes but not rating stars. I am using RatingView which creates rating stars stack. I am first showing not rated ones then rated stars. But when I change Movie card the star's color does not change

在此处输入图像描述


import SwiftUI

struct RatingView: View {
    
    @Binding var movie : Movie
    
    var body: some View {
        HStack{
            ForEach(0 ..< Int(movie.getLikers())) { item in
            
                Image("star")
                    .scaleEffect(1.5)
                    .padding(10)

            }
            ForEach(0 ..< Int(movie.getDislikers())) { item in

                Image("star.fill")
                    .scaleEffect(1.5)
                    .padding(10)

            }
            Text(movie.imageName)
        }
        
    }
}

change your ForEach constructor to use ForEach([Hashable])

if movie.getDislikers() returns [Hashable] and Movie is some sort of observed object, it will update. Here is my solution in a sample app.

struct SomeStruct: Hashable {
}



struct Sample: View {
@Binding var store: [SomeStruct]
var body: some View {
List {
   Section {
      ForEach(store, id: \.self) { (foo: SomeStruct) in
        HStack {
             Text(foo)
        }
}
}
}

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