Customize SwiftUI Button
• 5 min read
swiftui
Customize a SwiftUI Button by changing its label and applying modifiers to both the button and its label.
1. Button with a Simple Text Label
This is the most common way to create a button, where you change the color, font, and padding of the text.
struct CustomButtonExample1: View {
var body: some View {
Button(action: {
print("Default Text Button Tapped")
}) {
Text("Tap Me") // The label
.font(.title3)
.fontWeight(.bold)
.foregroundColor(.white) // Text color
.padding(.vertical, 12)
.padding(.horizontal, 30)
.background(Color.blue) // Background color
.cornerRadius(10)
}
}
}
2. Button with a Border and Transparent Background
This example uses the .stroke style for the background to create a border effect.
struct CustomButtonExample2: View {
var body: some View {
Button(action: {
print("Bordered Button Tapped")
}) {
Text("Download")
.font(.headline)
.foregroundColor(.purple) // Text color
.padding()
// Use .overlay and .stroke to create a colored border
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.purple, lineWidth: 3)
)
}
}
}
3. Button with an Image (Icon Button)
You can use a Text and an Image (often a SF Symbol) together inside an HStack to create a button label with an icon.
struct CustomButtonExample3: View {
var body: some View {
Button(action: {
print("Icon Button Tapped")
}) {
HStack {
Image(systemName: "hand.thumbsup.fill") // SF Symbol
Text("Like")
}
.font(.title2)
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(25)
.shadow(radius: 5)
}
}
}
4. Customizing the Button’s Interaction (Style)
For more advanced, reusable customization across your app, you can create a custom ButtonStyle. This is necessary if you want the button’s appearance to change automatically when it’s pressed (the “pressed state”).
// 1. Define a custom ButtonStyle
struct ScaleButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(15)
.background(Color.red)
.foregroundColor(.white)
.clipShape(Capsule())
// This modifier causes the button to shrink when pressed
.scaleEffect(configuration.isPressed ? 0.9 : 1.0)
.opacity(configuration.isPressed ? 0.7 : 1.0)
.animation(.easeOut(duration: 0.1), value: configuration.isPressed)
}
}
// 2. Apply the custom style to a Button
struct CustomButtonExample4: View {
var body: some View {
Button("Custom Style Button") {
print("Custom Style Tapped")
}
.buttonStyle(ScaleButtonStyle()) // Applying the style
}
}