History
Loading...
Loading...
August 31, 2025
ButtonStyle protocol to create reusable button appearances. Define once with struct MyButtonStyle: ButtonStyle and apply with .buttonStyle(MyButtonStyle()) to maintain consistent design across your app.This approach creates a reusable button style that responds to press states with smooth visual feedback, including scale and opacity changes that enhance user experience
struct PressableButtonStyle: ButtonStyle {
let baseColor: Color
let pressedScale: CGFloat
init(color: Color = .blue, pressedScale: CGFloat = 0.95) {
self.baseColor = color
self.pressedScale = pressedScale
}
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(.horizontal, 20)
.padding(.vertical, 12)
.background(baseColor)
.foregroundColor(.white)
.cornerRadius(8)
.scaleEffect(configuration.isPressed ? pressedScale : 1.0)
.opacity(configuration.isPressed ? 0.8 : 1.0)
.animation(.easeInOut(duration: 0.1), value: configuration.isPressed)
}
}
// Usage
Button("Press Me") {
print("Button tapped")
}
.buttonStyle(PressableButtonStyle(color: .green))Custom button styles promote design consistency, reduce code duplication, and provide better user feedback through visual state changes. The animation makes interactions feel more responsive and polished compared to default button behavior.