swift ColorPicker被触发两次,即使一个颜色只被选中一次



我需要创建一个由用户使用ColorPicker创建/选择的颜色数组,将其绑定到@State var tempColor变量,并将tempColor附加到所选颜色数组,但问题是行为不稳定。具体来说,有时相同的颜色被添加到数组中两次,即使一个颜色被选中/按下一次。

在将所选颜色添加到数组之前,我添加了一些逻辑来检查重复的颜色,但仍然将颜色添加两次到数组中。当按下ColorPicker并选择颜色时,这种行为在80%的情况下发生。

请问有什么办法可以解决这个问题吗?我代码:

struct ContentView: View {
@State var createdColors = [Color]()
@State var tempColor: Color = .white
var body: some View {
VStack {
ColorPicker("selected color", selection: $tempColor)
.padding(10)
ScrollView(.horizontal) {
HStack {
ForEach(createdColors, id: .self) { col in
Circle()
.fill(col)
.frame(width: 60, height: 60)
.padding(10)
}
}
}
}
.onChange(of: tempColor) { _ in
if createdColors.contains(tempColor) {
print("we have the color already (createdColors.count)")
} else {
createdColors.append(tempColor)
print("adding new color (createdColors.count)")
}
}
}
}

给系统一点休息。

struct ContentView: View {

@State var createdColors = [Color]()
@State var tempColor: Color = .white

var body: some View {
VStack {
ColorPicker("selected color", selection: $tempColor)
.padding(10)
Text("Currently ^[(createdColors.count) item](inflect: true)")
ScrollView(.horizontal) {
HStack {
ForEach(createdColors, id: .self) { col in
Circle()
.fill(col)
.frame(width: 60, height: 60)
.padding(10)
}
}
}
}
.onChange(of: tempColor) { newColor in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
if createdColors.contains(newColor) {
print("We have the (newColor.description) already. Total: (createdColors.count)")
} else {
createdColors.append(tempColor)
print("Adding new color to (createdColors.count)")
}
}
}
}
}

有更好的办法解决这个问题。这只是一个快速修复。

最新更新