【问题标题】:SwiftUI 4 - iOS 16: weird animation in a rating stars viewSwiftUI 4 - iOS 16:评级星星视图中的奇怪动画
【发布时间】:2022-11-14 11:46:36
【问题描述】:

我正在使用以下代码 sn-p 来显示一个简单的星级评分视图:

struct ContentView: View {
    @State var rating: Float = 1.0
    
    var body: some View {
        HStack(spacing: 4) {
            ForEach (0 ..< filledStarsCount, id: \.self) { index in
                Button {
                    rating = Float(index + 1)
                    
                } label: {
                    Image(systemName: "star.fill")
                }
              
            }
            
            ForEach (0 ..< emptyStarsCount, id: \.self) { index in
                Button {
                    rating = Float(index + filledStarsCount + 1)
                    
                } label: {
                    Image(systemName: "star")
                }
               
            }
        }
        .font(.title)
    }

    var emptyStarsCount: Int {
        filledStarsCount == 5 ? 0 : abs(5 - filledStarsCount  )
    }
    
    var filledStarsCount: Int {
        let rounded = Int(rating)
        if rounded > 5 { 
            return 5
        }
        else {
            return rounded
        }
    }
}

但是每当我点击一个空星时,视图会在 iOS 16 中以一种奇怪的方式重新绘制,并在 iOS 15.5 中重新绘制(带有一点闪光),这是该问题的视频截图:

可以复制粘贴代码以在 XCode 中按原样进行试用。

【问题讨论】:

    标签: ios animation swiftui


    【解决方案1】:

    奇怪的动画是因为您不应该使用具有动态范围的 ForEach View 结构(它不是 for 循环),例如0 ..&lt; filledStarsCount,它必须是一个静态范围,例如0 ..&lt; 5。原因是当使用索引作为 ID 时它无法跟踪更改,因为如果说有 5 个项目并且索引 0 处的项目被删除,仍然有一个索引为 0 的项目。所以只需创建 5 星位置并决定是否每个都应该有一个填充图像或没有,例如

    ForEach (0 ..< 5) { index in
        Button {
           rating = Float(index + 1)
        } label: {
           Image(systemName: rating < index ? "star.fill" : "star" ) // needs tested 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      相关资源
      最近更新 更多