Quantumorange

SwiftUI Button Styles

We can make simple Text button like this

Button("Touch Me"){
	print("That tickles")
}

Which is great, but it might not be quite what we want. We don't just have to use text, we put whatever we like in our button:

Button(action: { print("bug")}) {
            Image(systemName: "ladybug")
        }

What if we want to have a standard style of button that we can reuse throughout our app? Button has the buttonStyle view modifier which allows us to pass in a style to make the button look however we like. We make our own styles by conforming to the ButtonStyle protocol. We just need to implement the makeBody method:

struct BigButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View
    {
        HStack{
            Spacer()
            configuration
                .label
                .font(.largeTitle)
                .padding()
            Spacer()
        }
        .background(configuration.isPressed ? Color.black : Color.blue)
        .foregroundColor(Color.white)
        .cornerRadius(15)
    }
    
}

This will make a big blue button with rounded corners. The configuration gives us everything we need to build our button. The label property is the view that was passed in to the buttons initialiser. Now we can make a button in like this:

  Button(action:{ print("You can't miss!") }){
            Text("Big Button!")
        }
        .buttonStyle(BigButtonStyle())
        .padding()

In this example configuration.label is the Text view.

Tagged with: