قالب وردپرس درنا توس
Home / IOS Development / A beginner's guide to SwiftUI buttons

A beginner's guide to SwiftUI buttons



I don't think I need to explain what a button is. It is a very basic user interface control that you can find in all apps and has the ability to handle user touch and trigger a certain action. If you've 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 am going to go through this SwiftUI control, and you will learn the following techniques:

  1. How to create a simple button and handle user selections
  2. How to customize the button background, padding and font
  3. How to add frames to a button
  4. How to create a button with both image and text
  5. How to create a button with a gradient background and shadows
  6. How to create a full-width button [1
    9659008] Note: If you are new to SwiftUI, you can Check the introductory guide first.

    Creating a new project with SwiftUI enabled

    OK, let's start with the basics and create a simple button using SwiftUI. First, cancel Xcode and create a new project using the template Single View Application . Enter the name of the project. I set it to SwiftUIButton but you are free to use any other name. All you need to do is check the Use SwiftUI option.

      A Beginner's Guide for SwiftUI Buttons 1

    After saving the project, Xcode should load the ContentView.swift file and display a preview of the design tab. In case the preview does not appear, you can click the Continue button in the canvas.

      A Beginner's Guide for SwiftUI Buttons 2

    Creating a Simple Button with SwiftUI

    Creating a button is very easy using SwiftUI. Basically, you can use the code snippet below to create a button:

    When creating a button, you must enter two code blocks:

    1. What to do – The code to execute after the button is dropped or selected by the user.
    2. What the button looks like – the code block that describes the look and feel of the button.

    For example, if you just want to make the Hello World tag a button, you can update the code like this:

    Well Hello World text becomes a printable

      A beginner's guide for SwiftUI buttons 3

    The button cannot be typed in the design tab. To test it, click the Play button to run the app. However, to see the Hello World dropped the message, right-click the Play button and then select Debug Preview . You will see the message on the console when you press the button.

      A Beginner's Guide to SwiftUI Buttons 4

    Customizing the Button Font and Background

    Now that you know how to create a simple button, let's see how to customize the look and feel of the built-in modifiers. Say to change the background and text color, you can use background and foregroundColor modifiers like this:

    To change the font, use the font modifier and specify the font (e.g., .title ) is as follows:

    After the change, your button should look like the figure below.

      A beginner's guide to SwiftUI buttons 5

    As you can see, the button doesn't look very good. Wouldn't it be great to put some space around the text? To do so, you can use the padding modifier as follows:

    After making the change, the canvas should update the button accordingly. The button should now look much better.

      A beginner's guide to SwiftUI buttons 6

    Order of Modifiers is important

    One thing I want to highlight is that the modifier should be placed before background modifies. If you write the code as below, the end result will be different.

      A SwiftUI Button Beginner's Guide 7

    If you place the padding module to the background you can still add some paddings to the button, but without the preferred background color. If you're wondering why, read the modifiers like this:

    Conversely, the modifiers will work the same way if upholstery modifier is placed before background modifier: [19659229] Text ("Hello World")
    . padding () // 1. Add paddings
    .background (Color.purple) // 2. Change the background color to purple including padding
    .foregroundColor (.white) // 3. Set the foreground / font color to white
    .font (.title) // 4. Change font

    Text ( "Hello World" )

    . upholstery ([19659018]) // 1. Add upholstery

    . background ( Color . purple ) [19659023] // 2. Change the background color to purple including padding

    . foregroundColor (. white ) // 3. Set foreground / font color to white

    . font (. title ) // 4. Change font type

Add borders to button

It does not mean that the modification should always be in the beginning. It just depends on your button design. Let's say you want to create a button with borders like this:

  A beginner's guide to SwiftUI buttons 8

You can change the code for the Text control as below:

Here we put the foreground color to purple and then put some empty paddings around the text. The modifier is used to define the width and color of the border. If you want to round the corners, you can optionally give the corner radius. You can change the value of width and cornerRadius to change the button design.

Let me give you another example. Let's say, a designer shows you the following button design. How should you implement it with what you have learned? Before reading the next section, please take a few minutes to find out the solution.

  A beginner's guide to SwiftUI buttons 9

OK, here is the code you need:

We use two padding modifiers to create button design. The first upholstery together with the background modifier is to create a button with upholstery and purple background. padding (10) modifier adds extra padding around the button and the border modifies specifies to paint a rounded edge in purple.

Creating a button with images and text

So far we are only working with text buttons. In a real project, you may want to show you the designer of a button with an image. The syntax for creating an image button is exactly the same except that you use the Image control instead of the Text control like this:

For your convenience, we use the built-in SF symbols (ie, junk) to create the image button. We specify using .largeTitle in the font modifier to make the image slightly larger. Your button should look like this:

  A beginner's guide to SwiftUI buttons 10

Similarly, if you want to create a circular image button with a solid background color, you can use the modifiers we discussed earlier. The figure below shows you an example.

  A beginner's guide to SwiftUI buttons 11

You can use both text and image to create a button. Say you want to put the word "Delete" next to the icon. Replace the code like this:

Here we put both image and text control in a horizontal stack. This will post the garbage icon and Delete text side by side. The changes applied to HStack styled the background color, the padding and around the button corners. The figure below shows the resulting button.

  A beginner's guide to SwiftUI buttons 12

Creating a gradient background and shadow button

SwiftUI allows you to easily style the gradient background button. Not only can you have a specific color on the background modifier, you can easily apply a gradient effect for all buttons. All you need to do is replace the following code line:

With:

You can freely use your own colors to render the gradient effect. Let's say your designer tells you to use the following gradient (A sample gradient from uigradients.com):

  A sample gradient from uigradients.com

There are several ways to convert the color code from hex to the compatible format in Swift. Here I will show one of the approaches. In the project navigator, select the asset directory (ie Assets.xcassets ). Right-click the empty area (under AppIcon) and select New Color Set .

  Define a new color set in the asset directory

Next, select color carefully and click the Show Inspector button. Then click the Attributes icon to reveal the attributes of a color set. Enter the name for DarkGreen in the name field. In the section Color change the input method to 8-bit hexadecimal .

  A beginner's guide to SwiftUI buttons 13

You can now set the color code in the Hex field. For this demo, enter # 11998e to define the color. Repeat the procedures to define a different color set for # 38ef7d . You can name the color scheme LightGreen .

  A SwiftUI Button Beginner's Guide 14

Now that you have defined two color sets, let's go back to ContentView.swift and update the code. To use the color set, you just need to specify the color set name as follows:

To render the gradient with DarkGreen and LightGreen color scheme, all you need to update is wallpaper modify as follows: