Buttons in SwiftUI can be made in two ways depending on how they should look.
The simplest way to make a button is when it just contains some text: you pass in the title of the button, along with a closure that should be run when the button is tapped:
Button("Tap me!") {
print("Button was tapped")
}
If you want something more, such as an image or a combination of views, you can use this alternative form
Button(action: {
print("Button was tapped")
}) {
Text("Tap me!")
}
This is particularly common when you want to incorporate images into your buttons.
SwiftUI has a dedicated Image
type for handling pictures in your apps, and there are three main ways you will create them:
Image("pencil")
will load an image called “Pencil” that you have added to your project.Image(decorative: "pencil")
will load the same image, but won’t read it out for users who have enabled the screen reader. This is useful for images that don’t convey additional important information.Image(systemName: "pencil")
will load the pencil icon that is built into iOS. This uses Apple’s SF Symbols icon collection, and you can search for icons you like – download Apple’s free SF Symbols app from the web to see the full set.By default the screen reader will read your image name if it is enabled, so make sure you give your images clear names if you want to avoid confusing the user. Or, if they don’t actually add information that isn’t already elsewhere on the screen, use the Image(decorative:)
initializer.
Because the longer form of buttons can have any kind of views inside them, you can use images like this:
Button(action: {
print("Edit button was tapped")
}) {
Image(systemName: "pencil")
}
And of course you can combine these with stacks to make more advanced button layouts:
Button(action: {
print("Edit button was tapped")
}) {
HStack(spacing: 10) {
Image(systemName: "pencil")
Text("Edit")
}
}
Tip: If you find that your images have become filled in with a color, for example showing as solid blue rather than your actual picture, this is probably SwiftUI coloring them to show that they are tappable. To fix the problem, use the renderingMode(.original)
modifier to force SwiftUI to show the original image rather than the recolored version.
SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.