我有一个SwiftUI菜单下拉列表,该列表类似于选择器视图,供用户选择重量。选择重量时,菜单会恢复正常,但是所选重量会变成灰色,就像未选择一样。所以我遇到一个UI错误。重量应改为纯白色。
我必须再次单击菜单,所选的砝码会正常显示,而其他时候,它应有的作用。
如何解决所选重量不显示为灰色的方式?
这是我的模特:
struct Ball {
var weights = [
"12", "20", "23", "25", "28", "30", "36", "40", "43"
]
}
这是我的自定义菜单:
struct WeightMenuPicker: View {
let ball = Ball()
@State var selectedWeight: Int = .zero
var body: some View {
Menu {
ForEach(ball.weights.indices, id: \.self) { indice in
Button(action: {
selectedWeight = indice
}) {
HStack {
if selectedWeight == indice {
HStack {
Text("\(ball.weights[indice])")
Image(systemName: "checkmark")
}
}
else {
Text("\(ball.weights[indice])")
}
}
}}}
label: {
Text("\(ball.weights[selectedWeight])")
.fontWeight(.bold)
.frame(minWidth: 120, minHeight: 40, alignment: .center)
.font(.headline)
.foregroundColor(.white)
.multilineTextAlignment(.center)
}
.frame(width: 120, height: 40)
.background(Color.blue)
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
}
}
答案 0 :(得分:1)
这是一个固定的变体(强制刷新标签)。在Xcode 12 / iOS 14上进行了测试。
Text("\(ball.weights[selectedWeight])")
.fontWeight(.bold)
.frame(minWidth: 120, minHeight: 40, alignment: .center)
.font(.headline)
.foregroundColor(.white)
.multilineTextAlignment(.center)
.id(selectedWeight) // << here !!