如何让这些 SwiftUI 文本“按钮”在点击时改变颜色?

问题描述 投票:0回答:2

在 SwiftUI 中,如何使这些文本“按钮”在点击时改变颜色,但在移开手指时恢复颜色?

https://i.sstatic.net/1R0OJ.jpg

按钮代码如下所示:

    LazyVGrid(columns:
                Array(repeating:
                GridItem(.flexible(),
                spacing: 5),
                count: 2),
                spacing: 2) {
        
        ForEach(viewModel.productIngredients, id: \.self) { ingredient in
            
           Text(ingredient.name)
                .font(.system(size: 14))
                .fontWeight(.medium)
                .foregroundColor(.black)
                .padding(8)
                .background(RoundedRectangle(cornerRadius: 10).stroke(Color.black, lineWidth: 2))
                .padding(.top,5)
///             .background(self.selectedIngredient == ingredient ? Color.blue : Color.white)
                .onTapGesture {
                    self.didTap.toggle()
                    self.selectedIngredient = ingredient
                }
            }
    }
ios swift mobile swiftui
2个回答
5
投票

您可以使用自定义

ButtonStyle
来执行此操作:

struct ContentView : View {
    var body: some View {
        Button(action: {
            //Your action code, taken from the previous `onTapGesture` in the original code
            //didTap.toggle()
            //selectedIngredient = ingredient
        }) {
            Text("Ingredient")
                .fontWeight(.medium)
        }.buttonStyle(CustomButtonStyle(isSelected: false)) //could pass a parameter here like isSelected: selectedIngredient == ingredient from your original code
    }
}

struct CustomButtonStyle : ButtonStyle {
    var isSelected: Bool
 
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .font(.system(size: 14))
            .foregroundColor(.black)
            .padding(8)
            .background(RoundedRectangle(cornerRadius: 10)
                            .stroke(configuration.isPressed ? Color.red : Color.black, lineWidth: 2)
            )
            .padding(.top,5)
            //Could also modify style based on isSelected
    }
}

请注意,您的

Text
视图现在包裹在
Button
中,并指定了
CustomButtonStyle
的按钮样式。

CustomButtonStyle
内部,我使用三元表达式基于
RoundedRectangle
设置背景
configuration.isPressed
的颜色。

我还展示了如何传递另一个参数(

isSelected
),因为在你原来的示例中,你可能也想根据该参数有条件地执行操作。


更新显示列的完整工作示例:
struct Ingredient : Identifiable, Hashable {
    var id = UUID()
    var name = "Ingredient"
}

struct ContentView: View {
    
    @State var ingredients = [Ingredient(),Ingredient(),Ingredient(),Ingredient(),Ingredient(),Ingredient(),Ingredient(),Ingredient()]
    
    var body: some View {
        LazyVGrid(columns:
                    Array(repeating:
                            GridItem(.flexible(),
                                     spacing: 5),
                          count: 2),
                  spacing: 2) {
            
            ForEach(ingredients, id: \.self) { ingredient in
                
                Button(action: {
                    //Your action code, taken from the previous `onTapGesture` in the original code
                    //didTap.toggle()
                    //selectedIngredient = ingredient
                }) {
                    Text(ingredient.name)
                        .fontWeight(.medium)
                }.buttonStyle(CustomButtonStyle(isSelected: false))
            }
        }
    }
}

struct CustomButtonStyle : ButtonStyle {
    var isSelected: Bool
    
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .font(.system(size: 14))
            .foregroundColor(.black)
            .padding(8)
            .background(RoundedRectangle(cornerRadius: 10)
                            .stroke(configuration.isPressed ? Color.red : Color.black, lineWidth: 2)
            )
            .padding(.top,5)
        //Could also modify style based on isSelected
    }
}

0
投票

我发现了一种稍微简单的方法来更改 SwiftUI 中按钮的颜色

Button(
    action: {
            print("¡Hola, mundo!")
            }
      )
        {
          Text("¡Hola, mundo!")
          .foregroundColor(.blue)
         }
© www.soinside.com 2019 - 2024. All rights reserved.