Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add an Icon to a Button in SwiftUI
Written by Team Kodeco

To add an icon to a button in SwiftUI, you can leverage SF Symbols, which is a built-in library of thousands of icons provided by Apple. SF Symbols make it easy to enhance the visual appeal and functionality of your buttons.

struct ContentView: View {
  var body: some View {
    VStack {
      Button(action: {
        // Action to perform when the button is tapped
      }) {
        Label("Show Some Love!", systemImage: "heart.fill")
          .padding()
          .foregroundColor(.white)
          .background(Color.blue)
          .cornerRadius(10)
      }
    }
  }
}

Your preview should look like this:

Add an icon to your button with SF Symbols.
Add an icon to your button with SF Symbols.

Here’s how this code works:

  • You begin by embedding the button within a VStack to provide a vertical stack of views.
  • Inside the Button view, you specify the action to perform when the button is tapped. You can replace the comment with your desired functionality.
  • The Label view allows you to set a title for the button and provide an SF Symbol to use as an icon. In this example, you use the SF Symbol “heart.fill” to represent a filled heart icon.
  • By chaining modifiers to the Label, you can further customize the appearance of the button. You apply padding, set the foreground color to white, set the background color to blue and give the button rounded corners using the cornerRadius modifier. Feel free to adjust these modifiers to match your design preferences.

By using SF Symbols, you can easily enhance the visual appeal and usability of your buttons in SwiftUI. The extensive library of icons available through SF Symbols ensures that you can find the perfect icon to represent various actions and concepts in your app. Enjoy adding icons to your buttons and giving them a personalized touch!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.