2

这是我的按钮:

                    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)

                }

我需要防止它在禁用时淡出,并赋予它不同的颜色

4

1 回答 1

3

这是基于自定义按钮样式的解决方案(所有颜色仅用于演示,但方法无关紧要)。使用 Xcode 11.4 / iOS 13.4 测试

在此处输入图像描述

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))
        }

    }
}
于 2020-05-24T12:50:14.567 回答