Kevin
Kevin

Reputation: 1243

Prevent button fading out when it's disabled in SwiftUI

this is my button:

 Button(action: {
     print("pressing the button")
 }) {
     ZStack {
         LinearGradient(gradient: Gradient(colors: [Color("homeBG2"), Color("homeBG1")]), startPoint: .leading, endPoint: .trailing)
         Text("Login").fontWeight(.semibold).animation(.none)
     }
 }
 .frame(width: geo.size.width*0.74, height: 50)
 .cornerRadius(20)
 .shadow(color: Color.black.opacity(0.24), radius: 4, x: 0, y: 3)
 .buttonStyle(PlainButtonStyle())
 .disabled(!self.allowLogin)  

I need to prevent it from fading out when it is disabled, and give it a different color

Upvotes: 3

Views: 3084

Answers (1)

Asperi
Asperi

Reputation: 258471

Here is a solution based on custom button style (all colors are just for demo, but it does not matter for approach). Tested with Xcode 11.4 / iOS 13.4

enter image description here

struct LoginButtonStyle: ButtonStyle {
    var state: Bool
    var normalColor: Color = .blue
    var alternateColor: Color = .gray
    var disabledColor: Color = .red

    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(state ? (configuration.isPressed ? alternateColor : normalColor) : disabledColor)
    }
}

struct TestLoginButtonStyle: View {
    @State private var allowLogin = true
    var body: some View {
        VStack {
            Button("Test") { self.allowLogin.toggle() }

            Divider()

            Button(action: {
                    print("pressing the button")
                }) {
                    Text("Login")
                }
                .cornerRadius(20)
                .shadow(color: Color.black.opacity(0.24), radius: 4, x: 0, y: 3)
                .buttonStyle(LoginButtonStyle(state: self.allowLogin))
        }

    }
}

Upvotes: 3

Related Questions