首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SwiftUI -如何在按下on按钮时更改所有其他按钮的颜色?

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

Stack Overflow用户
提问于 2019-11-08 00:02:35
回答 2查看 1.4K关注 0票数 4

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

代码语言:javascript
运行
复制
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)
          }
        }
      }
    }
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-08 00:56:21

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

代码语言:javascript
运行
复制
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更改时,依赖于该状态的所有按钮都将相应更新。

票数 9
EN

Stack Overflow用户

发布于 2019-11-08 00:51:10

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58752639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档