Hello SwiftUI Learners,
I have been a away for a while and just realized that this newsletter has grown to over 200 subscribers. Which is really fun to see and it gave me some motivation to start providing content on this newsletter again.
I have also been thinking about adding a personal touch to this newsletter as I guess a lot more people are in the same situation as me. Which is, trying to learn how to code while having a full-time job and family. It aint easy to find the time I tell you.
But for this week I will start with another code example. So let’s dig in! This is what we will create today.
In this issue, we will explore how to create a set of buttons in SwiftUI that allows users to select one option from multiple options. We will also add a small animation to enhance the user experience when a button is selected.
We will start by defining a simple data model to represent our options.
struct Option: Identifiable {
let id = UUID()
let title: String
}
Next, create an array of options that we will display as buttons.
let options = [
Option(title: "Option 1"),
Option(title: "Option 2"),
Option(title: "Option 3")
]
Now, let's build the UI with buttons for each option. We will have 3 buttons to select from and once pressed, they will transition from a gray color to blue.
struct SingleSelectionButton: View {
@State private var selectedOption: Option?
var body: some View {
VStack {
ForEach(options) { option in
Button(action: {
withAnimation {
selectedOption = option
}
}) {
Text(option.title)
.padding()
.background(selectedOption == option ? Color.blue : Color.gray)
.foregroundColor(.white)
.cornerRadius(8)
.scaleEffect(selectedOption == option ? 1.1 : 1.0)
}
.padding(.vertical, 4)
}
}
.padding()
}
}
In the code above, we have a standard animation for when a button is selected. We can add some more flavor to it with the .easeInOut modifier. Replace the withAnimation with this code instead:
withAnimation(.easeInOut(duration: 0.3)) {
selectedOption = option
}
You final code should look like this:
struct SingleSelectionButton: View {
@State private var selectedOption: Option?
var body: some View {
VStack {
ForEach(options) { option in
Button(action: {
withAnimation(.easeInOut(duration: 0.3)) {
selectedOption = option
}
}) {
Text(option.title)
.padding()
.background(selectedOption == option ? Color.blue : Color.gray)
.foregroundColor(.white)
.cornerRadius(8)
.scaleEffect(selectedOption == option ? 1.1 : 1.0)
}
.padding(.vertical, 4)
}
}
.padding()
}
}
struct Option: Identifiable, Equatable {
let id = UUID()
let title: String
}
let options = [
Option(title: "Option 1"),
Option(title: "Option 2"),
Option(title: "Option 3")
]
#Preview {
SingleSelectionButton()
}
That was it for this weeks post, hope you learned something new.
Have a nice day and keep on learning!
/Mr SwiftUI