繁体   English   中英

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

[英]SwiftUI - How to change the colour of all other buttons when pressing on button?

在我的代码下面,我有一个设置,其中有 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)
          }
        }
      }
    }
  }
}

在 SwiftUI 中,一切都由 state 更改触发。 要实现单选按钮样式更改,您需要执行以下操作:

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)
        }
    }
}

当共享的 currentSelectedId 更改时,依赖于 state 的所有按钮将相应更新。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM