Skip to content

Instantly share code, notes, and snippets.

@bencmorrison
Last active June 10, 2023 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bencmorrison/7d9a2eed0bc181e6c1101f107158184b to your computer and use it in GitHub Desktop.
Save bencmorrison/7d9a2eed0bc181e6c1101f107158184b to your computer and use it in GitHub Desktop.
SwiftUI ButtonStyle with Disabled State
// Created by Ben Morrison on 31/5/2023.
import SwiftUI
/// Create a custom button style that as you normally do
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
// This is differnet as you will not apply your changes here
// We will return a view that takes the configuration instead
CustomButtonStyleView(configuration: configuration)
}
/// Custom view that will contain all the changes for your
/// button, including the disabled state.
private struct CustomButtonStyleView: View {
// Binds to the view's `isEnabled` to allow updates for disabled.
@Environment(\.isEnabled) var isEnabled: Bool
// The configuration from the CustomButtonStyle's makeBody(configuration:)
let configuration: ButtonStyle.Configuration
var body: some View {
configuration.label
.padding()
.foregroundColor(isEnabled ? .green : .black)
.background(isEnabled ? .black : .gray)
.cornerRadius(8.0)
}
}
}
extension ButtonStyle where Self == CustomButtonStyle {
/// Allows us to use `.customButton` in the `buttonStyle()` function
static var customButton: CustomButtonStyle { CustomButtonStyle() }
}
/// Mark: - Usage Example
Button {
// some action
} label: {
Text("Custom Button")
}
.buttonStyle(.customButton)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment