我需要连续显示3个按钮,按钮的默认边框颜色为绿色(例如绿色)。根据单击的三个按钮中的哪个按钮,我需要更改其边框颜色(变为红色)以突出显示该按钮。 SwiftUI不允许在动作处理程序中传递按钮对象(自身)(如Swift中的“发送者”)。有没有一种方法可以根据选择的哪个来切换所有三个按钮的边框?
HStack {
Button(action: {
border(Color.red, width: 1) // This doesn't work
}
, label: {
Text("Option 1")
}).border(Color.green, width: 1)
Button(action: {
border(Color.red, width: 1)
}
, label: {
Text("Option 2")
}).border(Color.green, width: 1)
Button(action: {
border(Color.red, width: 1)
}
, label: {
Text("Option 3")
}).border(Color.green, width: 1)
}
答案 0 :(得分:1)
解决方案应如下所示:
@State var selectedButton: Int = 1
var body: some View {
HStack {
Button(action: {
selectedButton = 1
}
, label: {
Text("Option 2")
})
.border(selectedButton == 1 ? Color.red : Color.green, width: 1)
Button(action: {
selectedButton = 2
}
, label: {
Text("Option 2")
})
.border(selectedButton == 2 ? Color.red : Color.green, width: 1)
Button(action: {
selectedButton = 3
}
, label: {
Text("Option 3")
})
.border(selectedButton == 3 ? Color.red : Color.green, width: 1)
}
}