In a project, you or your designer may want to display a button with an image. The syntax for creating a button with an image is almost the same except that you have to use the Image control instead of Text, as seen in the following example:
Button(action: {
print("Delete button tapped!")
}) {
Image(systemName: "trash")
.font(.largeTitle)
.foregroundColor(.red)
}
in which we use the SF Symbols library to create a button with an image. In this example we use the “trash can” symbol as the image. To make the image slightly larger we use the .largeTitle option in the font modifier. The resulting button should look like this:
Similarly, if you wanted to create a button with a circular image and a solid color as a background, you can do so by applying the following modifiers:
import SwiftUI
struct ContentView: View {
var body: some View {
Button {
print("Hello World tapped!")
} label: {
Button(action: {
print("Delete button tapped!")
}) {
Image(systemName: "trash")
.padding()
.background(.red)
.clipShape(Circle())
.font(.largeTitle)
.foregroundColor(.white)
}
}
}
}
which results in the following:
We can use text and images to create a button in SwiftUI. Imagine you want to put the word “Delete” next to the trash can image, as in the following example:
In this code snippet we embed both the image and the text in a horizontal stack (HStack). This arrangement allows the trash can icon and the Delete text to be displayed together.
import SwiftUI
struct ContentView: View {
var body: some View {
Button {
print("Hello World tapped!")
} label: {
Button(action: {
print("Delete button tapped!")
}) {
HStack{
Image(systemName: "trash")
.font(.title)
Text("Delete")
.fontWeight(.semibold)
.font(.title)
}
.padding()
.foregroundStyle(.white)
.background(.red)
.cornerRadius(40)
}
}
}
}
On the other hand, the modifiers applied to the HStack specify the background color, padding, and rounded corners of the button.
1 comment