Skip to content

Instantly share code, notes, and snippets.

@juliensagot
Created October 10, 2024 17:37
Show Gist options
  • Save juliensagot/cee7f6cfa7efffe9faf77300bd481b20 to your computer and use it in GitHub Desktop.
Save juliensagot/cee7f6cfa7efffe9faf77300bd481b20 to your computer and use it in GitHub Desktop.
SwiftUI custom ButtonStyle example
import SwiftUI
struct CapsuleButtonStyle: ButtonStyle {
enum Appearance {
case plain
case outlined
}
let appearance: Appearance
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundStyle(.primary)
.fontWeight(.semibold)
.padding()
.background {
switch appearance {
case .plain:
ContainerRelativeShape()
.foregroundStyle(.secondary)
case .outlined:
ContainerRelativeShape()
.stroke(.secondary, lineWidth: 2)
}
}
.containerShape(Capsule())
}
}
extension ButtonStyle where Self == CapsuleButtonStyle {
static func capsule(appearance: CapsuleButtonStyle.Appearance = .plain) -> Self {
return CapsuleButtonStyle(appearance: appearance)
}
}
#Preview {
VStack(spacing: 32) {
Button(action: {}) {
Text("Button Label")
}
.buttonStyle(.capsule())
.foregroundStyle(.white, .red.gradient)
Button(action: {}) {
Label("Button Title", systemImage: "paperplane.fill")
}
.buttonStyle(.capsule(appearance: .outlined))
.foregroundStyle(.tint)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment