所以我做一个简单的餐厅账单分割应用程序,我有一个按钮,我想突出当用户点击它。我还希望其他按钮不突出显示。在UIKit中,使用sender.currentTitle.
可以很简单地做到这一点这是我的代码按钮struct TipButton: View, Identifiable {
var id: Int
var tipPercentage: String
@State var didTap: Bool = false
@State var buttonLetter: String
@State var zeroPctButton: Bool = false
@State var tenPctButton: Bool = false
@State var twentyPctButton: Bool = false
var body: some View {
Button {
print("Tip is... (Float(tipPercentage) ?? 7.7)")
didTap.toggle()
if buttonLetter == "A" {
zeroPctButton = true
tenPctButton = false
twentyPctButton = false
}
else if buttonLetter == "B" {
didTap = true
}
} label: {
Text("(tipPercentage)%")
.font(.largeTitle)
.bold()
}
.background(didTap ? Color.green : Color.clear)
}
}
到目前为止,我一直在摆弄它,并为百分比金额添加了不同的东西,如可识别和@状态变量,但无法弄清楚。
在我的主文件中,我将与这些按钮一起构建视图,例如
struct ButtonsView: View {
var body: some View {
//blah blah
//some UI arranging code
TipButton(id: 1, tipPercentage: "0", buttonLetter: "A")
TipButton(id: 2, tipPercentage: "10", buttonLetter: "B")
TipButton(id: 3, tipPercentage: "20", buttonLetter: "C")
}
}
如你所见,我尝试了id
和buttonLetter
简而言之,我想点击按钮A,让它高亮,然后当我点击按钮B时,它高亮,按钮A不再高亮
为了做到这一点,您需要将@State
从子视图移动到父视图。然后,您可以通过Binding
与子视图共享它。
在这个例子中,我有一个@State
变量,它存储突出显示的id
。当按钮被按下时,它只是更新值。
struct TipButton: View, Identifiable {
var id: Int
var tipPercentage: String
@Binding var highlightedID : Int
var body: some View {
Button {
highlightedID = id
print("Tip is... (Float(tipPercentage) ?? 7.7)")
} label: {
Text("(tipPercentage)%")
.font(.largeTitle)
.bold()
}
.background(id == highlightedID ? Color.green : Color.clear)
}
}
struct ButtonsView: View {
@State private var highlightedID : Int = 3
var body: some View {
TipButton(id: 1, tipPercentage: "0", highlightedID: $highlightedID)
TipButton(id: 2, tipPercentage: "10", highlightedID: $highlightedID)
TipButton(id: 3, tipPercentage: "20", highlightedID: $highlightedID)
}
}