A Beginner’s Guide to SwiftUI Buttons
I don’t think I need to explain what a button is. It’s a very basic UI control that you can find in all apps and has the ability to handle users’ touch, and trigger a certain action. If you have learned iOS programming before, Button
in SwiftUI is very similar to UIButton
in UIKit. It’s just more flexible and customizable. You will understand what I mean in a while. In this tutorial, I will go through with you this SwiftUI control and you’re to learn the following techniques:
- How to create a simple button and handle the user’s selection
- How to customize the button’s background, padding and font
- How to add borders to a button
- How to create a button with both image and text
- How to create a button with a gradient background and shadows
- How to create a full-width button
Note: If you’re new to SwiftUI, please check out the introductory tutorial first.
Creating a New Project with SwiftUI enabled
Okay, let’s start with the basics and create a simple button using SwiftUI. First, fire up Xcode and create a new project using the Single View Application template. Type the name of the project. I set it to SwiftUIButton but you’re free to use any other name. All you need to ensure is check the Use SwiftUI option.