How to create and style Buttons in SwiftUI

Share on facebook
Share on twitter
Share on pinterest

Wanna know how to create and customize a Button in SwiftUI that triggers specific code when being touched? Here you go! 👇

Step 1: Create the Object you want inside your Button, for example a Text. If you want more than one object inside your Button, you can group them using, for instance, a HStack. You can now apply modifiers for customizing the created objects.

import SwiftUI

struct ContentView : View {
    var body: some View {
        HStack {
            Text("ADD TO CART")
                .font(.custom("Avenir-Medium", size: 20))
                .foregroundColor(.black)
            Image(systemName: "cart")
                .foregroundColor(.black)
        }
    }
}

Step 2: If you nested multiple objects, you have to apply the overall modifiers like the Buttons frame size or background color to the Stack.  If you have only one object, simply apply these modifiers to the object itself.

struct ContentView : View {
    var body: some View {
        HStack {
            Text("ADD TO CART")
                .font(.custom("Avenir-Medium", size: 20))
                .foregroundColor(.black)
            Image(systemName: "cart")
                .foregroundColor(.black)
        }
            .frame(width: 220, height: 30)
            .padding()
            .background(Color.green)
            .cornerRadius(10.0)
    }
}

Step 3: Wrap everything into a Button. Insert the action parameter followed by curly braces. Inside these braces you can execute for example a print statement or a custom function.

import SwiftUI

struct ContentView : View {
    var body: some View {
        Button(action: {print("Button touched!")}) {
            HStack {
                Text("ADD TO CART")
                    .font(.custom("Avenir-Medium", size: 20))
                    .foregroundColor(.black)
            Image(systemName: "cart")
                    .foregroundColor(.black)
            }
                .frame(width: 220, height: 30)
                .padding()
                .background(Color.green)
                .cornerRadius(10.0)
        }
    }
}

Run your app by starting the live mode of the Preview Simulator!

mIf you liked this tutorial, feel free to check out our Mastering SwiftUI eBook. In this book, we also created a To-Do app by using the mentioned Core Data functionalities!

I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, check out our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount

small_c_popup.png

Are you ready for a new era of iOS development?

Start learning swiftUI today - download our free e-book