SwiftUI - 按下按钮时如何更改所有其他按钮的颜色? [英] SwiftUI - How to change the colour of all other buttons when pressing on button?

查看:29
本文介绍了SwiftUI - 按下按钮时如何更改所有其他按钮的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码下面,我有一个设置,其中有 4 个按钮,每次我按下一个按钮时,它都充当一个切换按钮(就像一个单选按钮).我想要实现的是在按下其中一个按钮时将所有其他按钮变为灰色.一次只能有一个按钮为绿色或处于活动状态.

Below in my code I have a setup where there are 4 Buttons, each time I press a button it acts as a toggle (like a radio button). What I would like to achieve is to turn all other buttons grey when pressing on one of the buttons. Only one button can be green or active at a time.

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 中,一切都是由状态更改触发的.要实现单选按钮样式更改,您需要执行以下操作:

In SwiftUI everything is triggered by a state change. To implement a radio-button style change you'll need to do something like:

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 发生变化时,所有依赖于该状态的按钮都会相应地更新.

When the shared currentlySelectedId changes, all buttons dependent on that state will update accordingly.

这篇关于SwiftUI - 按下按钮时如何更改所有其他按钮的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆