【问题标题】:Binding variable in ForEach not updateForEach 中的绑定变量未更新
【发布时间】:2020-07-14 22:42:18
【问题描述】:

我想在单击另一张电影卡时更改评级明星的图像。其他文字信息会发生变化,但星级不会发生变化。我正在使用 RatingView 创建评级星堆栈。我首先展示的是未评级的,然后是评级的明星。但是当我更换电影卡时,星星的颜色并没有改变


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

【问题讨论】:

  • 您能否发布您的Move struct/class,这将有助于我们进一步调查。
  • 不要使用函数,比如getLikers() - 使用属性。
  • 代码似乎是正确的。您还可以添加使用RatingView 的地方的代码吗?我怀疑问题可能隐藏在那里。

标签: ios swift swiftui


【解决方案1】:

将您的 ForEach 构造函数更改为使用 ForEach([Hashable])

如果movie.getDislikers() 返回[Hashable] 并且Movie 是某种观察到的对象,它将更新。这是我在示例应用中的解决方案。

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

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 1970-01-01
    • 2013-08-03
    • 2016-08-25
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多