Hello SwiftUI learners,
A new week is coming to an end, hope you had a great week and are ready for the next one!
In this post you will learn how to pimp up your button by using the button style protocol. The result will be a small but neat change to the buttons behavior.
How the button will behave when we are done:
First we need to create our button. And the normal button behavior is what you can see in the video below.
struct ButtonStyleView: View {
@State private var pressButton: Bool = false
var body: some View {
VStack {
Button(action: {
pressButton.toggle()
}, label: {
Text("Press me")
.font(.title2)
.foregroundColor(.white)
.padding(.vertical)
.frame(maxWidth: .infinity)
.background(
Color.green
.cornerRadius(8)
)
})
}
.padding()
}
}
Want to learn more about SwiftUI animations?
I created a book for anyone that want to develop their SwiftUI animation skills. The book cover the basics and more advance techniques to animating objects and views in SwiftUI. Start learning today and get a 30% discount by clicking the link below:
Book Deal! 30% Discount for Learning SwiftUI Animations - The Beginner Roadtrip
What I just learned is a pretty small but neat effect that I most likely will start using in my apps moving forward. Let’s say you want the button to shrink a bit once you press it? That can be achieved with the button style protocol.
Add this struct to your code.
struct ScaleButtonPress: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(x: configuration.isPressed ? 0.98 : 1, y: configuration.isPressed ? 0.98 : 1)
}
}
By adding a small scale effect to the label, the button will shrink slightly once it is pressed. Now you need to add this to your button by using the button style modifier. Your final code should look like this now.
struct ButtonStyleView: View {
@State private var pressButton: Bool = false
var body: some View {
VStack {
Button(action: {
pressButton.toggle()
}, label: {
Text("Press me")
.font(.title2)
.foregroundColor(.white)
.padding(.vertical)
.frame(maxWidth: .infinity)
.background(
Color.green
.cornerRadius(8)
)
})
.buttonStyle(ScaleButtonPress())
}
.padding()
}
}
struct ScaleButtonPress: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(x: configuration.isPressed ? 0.98 : 1, y: configuration.isPressed ? 0.98 : 1)
}
}
As you can see in the video at the start of this post, the change is small but yet subtle.
What do you think? I must say I like it, and obviously there are a ton of different ways you can use the button style protocol to customize your button. I urge you to try some out.
If you already know a thing or two about this subject, please share it in the comment section. Would love to check it out.
Have a nice day!
Mr SwiftUI