Better Programming

Advice for programmers.

Follow publication

Member-only story

3 Ways to Style SwiftUI Buttons

Kristaps Grinbergs
Better Programming
Published in
3 min readSep 24, 2021

Photo by Derek Baumgartner on Unsplash.

Using mobile apps, we navigate to another view, calculate business expenses, or send a tweet by tapping on a button. SwiftUI makes it a breeze to construct a button.

This time we will talk about how to do it in three ways:

  • using the view modifier approach
  • building a custom view modifier
  • applying the button style

We are going to start with the most basic SwiftUI button and style.

Button("Continue", action: {})

Using a Custom View Modifier

In SwiftUI view modifiers are used to change the view in some kind of way. We can build custom view modifiers ourselves. We will try to build one to create a custom button.

At first, we need to create the custom modifier. To do that we should use the ViewModifier protocol that requires implementing one function func body(content: Content) -> some View which takes in a view and produces a different version of that view.

struct CustomButtonModifier: ViewModifier {
func body(content: Content) -> some View {
content
.font(.title)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.clipShape(RoundedRectangle(cornerRadius: 20))
}
}

We can apply the newly made view modifier with a .modifier modifier to the original view, but we can create an extension to the View protocol. That would allow us to use it in a more shorthand way.

extension View {
func customButton() -> some View {
modifier(CustomButtonModifier())
}
}

We can create a SwiftUI button view now and apply our freshly created view modifier.

Button("Continue", action: {})
.customButton()

Building a Custom View

Now let’s look into how we can style a SwiftUI button by building a custom view. We need to create a custom view that we will pass into label

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Kristaps Grinbergs
Kristaps Grinbergs

Written by Kristaps Grinbergs

Blockchain, mobile and fullstack developer. Startup founder. Conference speaker. Mentor. Passionate about building products, sustainability and Web 3.0.

Responses (1)

Write a response

When you do make a custom button style, don't you lose the "feedback" supplied by the standard button (it dims slightly when pressed)?

--