Adding a label UI element

Let's add a new UI element, that is, a label, to show notifications to users. For that, follow these steps:

  1. Open Main.storyboard and open the library button located in the top-right corner of the screen (the first button of its set, with a square inside a circle):

Library button
  1. Find and drag a Label onto the view:

Selecting the Label from the library
  1. With the label selected, use Ctrl + mouse drag to create constraints for the label regarding the view, or in the toolbar below the phone view, click on the Add New Constraints button. Constraints help us fix the elements on the screen so that they appear properly on any device screen and in any orientation.
  2. Then, modify the values of the left, right, and bottom constraints to 20, 20, and 0respectively (the icon of the constraint will turn a bright red). Check the Height constraint box and set it to 60, as follows:

Adding constraints to the label
  1. The new constraints will appear on the right-hand side window, under the Show the Size Inspector tab, as follows:

The four new constraints added at the bottom of the Show the Size tab
  1. In the Show the Attributes Inspector tab, delete the default Text, set the label Color to green, check the Dynamic Type checkbox, and set the Alignment of the text to centered, as follows:

Changing the properties of the label
  1. To connect the label to our ViewController.swift script and use it in our methods, click on the Show the Assistant Editor button in the top-right corner (two circles intersecting) to open the script:

Selecting the Assistant Editor
  1. Press Ctrl + drag the label (you will see a blue line as you drag the mouse) from the hierarchical view to the code, below the sceneView variable. Release the mouse. Then, on the pop-up window shown in the following screenshot, enter the Name of the variable, which will be infoLabel in this case, and click Connect:

The label from the UI will be attached to the infoLabel variable
  1. Open the ViewController.swift file to check that the new variable has been added correctly, as follows:
@IBOutlet weak var infoLabel: UILabel!

Now, we can start sending messages to the user through the interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.4