SwiftUI - 如何在按下按钮时更改所有其他按钮的颜色?

6

在我的代码中,我设置了4个按钮,每次按下一个按钮时,它会像单选按钮一样切换状态。我的目标是,在按下其中一个按钮时将所有其他按钮变为灰色。同时只能有一个按钮呈绿色或处于活动状态。

struct hzButton: View {
  var text: String
  @State var didTap: Bool

  var body: some View {
    Button(action: {
      if self.didTap == true{
        self.didTap = false
      }else{
        self.didTap = true
      }
      selectFreq(frequency: self.text)
    }) {
      Text(text)
        .font(.body)
        .fontWeight(.semibold)
        .foregroundColor(Color.white)
        .multilineTextAlignment(.center)
        .padding(.all)
        .background(didTap ? Color.green : Color.gray)
        .cornerRadius(6.0)
    }
    .frame(width: nil)
  }
}

struct Row: Identifiable {
  let id = UUID()
  let headline: String
  let numbers: [String]
}

struct ContentView: View {
  var rows = [
    Row(headline: "", numbers: ["250","500","750","1000"]),
  ]
  var body: some View {
    HStack {
      ForEach(rows) { row in
        HStack {
          ForEach(row.numbers, id: \.self) { text in
            hzButton(text: text, didTap: false)
          }
        }
      }
    }
  }
}
2个回答

11

在SwiftUI中,一切都是由状态变化触发的。要实现单选按钮样式的更改,您需要执行类似以下操作:

struct MyRadioButton: View {
    let id: Int
    @Binding var currentlySelectedId: Int
    var body: some View {
        Button(action: { self.currentlySelectedId = self.id }, label: { Text("Tap Me!") })
            .foregroundColor(id == currentlySelectedId ? .green : .red)
    }
}


struct MyRadioButtons: View {
    @State var currentlySelectedId: Int = 0
    var body: some View {
        VStack {
            MyRadioButton(id: 1, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 2, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 3, currentlySelectedId: $currentlySelectedId)
            MyRadioButton(id: 4, currentlySelectedId: $currentlySelectedId)
        }
    }
}

当共享的currentlySelectedId更改时,所有依赖于该状态的按钮都将相应更新。


谢谢@Michael!我已经找了几周了,终于找到了!虽然它能用,但我希望更好地理解它的逻辑...如果你有时间,我真的很感激如果你能提供更详细的解释(特别是@Binding部分),或者指向一个更好地解释这个概念的资源。 - Matvey

1

不要将其视为4个单独的按钮,每个按钮都有自己的开/关状态,而是将其视为一个整体,考虑它们如何代表一个单一的当前值状态。然后,当每个按钮确定其背景颜色时,它可以考虑“我的值是否与当前选择的值匹配?”因此,不要在点击按钮时切换布尔值,而应该让按钮使用自己的值更新当前选择的值(在组中共享所有按钮的值)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接