Customize the Appearance of a Button in SwiftUI
Written by Team Kodeco
It’s important to customize the appearance of a button to make it consistent with the overall design of your app. SwiftUI makes this easy.
Here’s an example:
struct ContentView: View {
var body: some View {
Button("Press Me!") {
// Button action goes here
}
.padding()
.background(.orange)
.foregroundColor(.white)
.font(.title2)
.clipShape(RoundedRectangle(cornerRadius: 10))
}
}
Your preview should look like this:
This code creates a button in SwiftUI and applies a number of modifiers to change its appearance and functionality.
Here is a breakdown of the code:
-
Button("Press Me!") { }
creates a newButton
with the title Press Me!. The text within the{}
is the action that will be executed when the button is pressed. In this case, there is no action defined yet. -
.padding()
adds padding around the button. Padding is space around the content of a view, which is the button in this case. Without any arguments, it adds a system default amount of space on all sides of the button. -
.background(.orange)
sets the background color of the button to orange. -
.foregroundColor(.white)
sets the color of the text of the button to white. -
.font(.title2)
sets the font of the button’s title totitle2
, which is a predefined font style that is smaller thantitle
but larger thanheadline
. -
.clipShape(RoundedRectangle(cornerRadius: 10))
clips the button into the shape of a rectangle with rounded corners. ThecornerRadius: 10
means the corners of the rectangle will be rounded with a radius of 10.
One thing to note is that these modifiers are applied in order. So, for example, the padding is applied first, then the background color, and so on. The order of these modifiers can sometimes affect the resulting appearance. In this case, the button will have padding, then the background color will cover the button and its padding, and then the clipping will be applied to the button including its padding.
This would produce a button with white text saying “Press Me!”, an orange background, a bit of padding around the text, and rounded corners.
To summarize, you can customize the appearance of a button in SwiftUI by modifying its background and foreground colors, font styling and corner radius. Use the background
, foregroundColor
, font
and clipShape
modifiers to achieve this.