【问题标题】:SWIFTUI. How to permanently change the color of the buttons after clicking?斯威夫特。单击后如何永久更改按钮的颜色?
【发布时间】:2019-10-26 23:33:30
【问题描述】:

我正在构建一个测验应用程序。一个问题; 3个答案。答案位于单独的按钮中。

我管理了单击时更改按钮的颜色。例如从灰色到绿色/红色。但点击后按钮变回灰色。

有没有办法在点击后保留更改的颜色,比如 HTML 中的超链接?

这是样式代码:

struct MyButtonStyle: ButtonStyle {

  func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
      .padding(20)
      .foregroundColor(.white)
      .background(configuration.isPressed ? Color.red : Color.gray)
      .cornerRadius(10.0)

【问题讨论】:

    标签: button colors swiftui


    【解决方案1】:

    您可以像这样声明您的 ButtonStyle:

    public struct SelectedButtonStyle: ButtonStyle {
    
        @Binding var isSelected: Bool
    
        public func makeBody(configuration: Self.Configuration) -> some View {
            configuration.label
                .padding(20)
                .foregroundColor(.white)
                .background(isSelected ? Color.red : Color.gray)
                .cornerRadius(10.0)
        }
    }
    

    然后在视图中,为选择设置一个状态:

    @State var isSelected = false
    

    然后您可以像这样声明您的按钮,使其被选中一次并永远保持选中状态:

    Button("Tap") {
        self.isSelected = true
    }   .buttonStyle(SelectedButtonStyle(isSelected: $isSelected))
    

    或者你可以这样声明它也可以取消选择它:

    Button("Tap") {
        self.isSelected.toggle()
    }   .buttonStyle(SelectedButtonStyle(isSelected: $isSelected))
    

    【讨论】:

      【解决方案2】:

      尝试这样的操作,一旦isPressed 变为true 它就不会再次变为假,所以按钮将保持灰色

      struct ContentView: View {
      
         @State private var isPressed = false
      
          var body: some View {
              Button(action: {
                  self.isPressed = true
              }, label: {
                  Text("Button").accentColor(isPressed ? Color.gray : Color.blue)
              })
          }
      }
      

      【讨论】:

      • 我试过了,但是点击后颜色又变回来了。感谢您的努力。
      • @IrfanKaya 你试过这个代码吗?再次点击按钮时isPressed不会变成false,所以颜色不会改变
      • 我不知道为什么,但我无法让它工作。我对这些东西很陌生,所以也许还有其他代码可以做到这一点。
      • 使用self.isPressed.toggle()
      猜你喜欢
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 2020-01-01
      相关资源
      最近更新 更多