1.3. UITextField, and constraints
So far, we have added one UILabel, with the text "Hello World" in it. Now, we will add our second UI element on the screen, UITextField, below the Label. UITextField is used to get user inputs from the keyboard. We can type something in the TextField and use it in our app.
Housekeeping the constraints first
So far, the Label is center-aligned both horizontally and vertically. We will keep the horizontal alignment for the Label but remove the vertical alignment. Unfortunately, the storyboard can't clear one particular constraint from visual tools (or not easily). (That's another reason why we will move to write constraints programmatically). So, we will clear all the constraints from the Label. Click on the 'Reset constraints' tool, and select Clear Constraints for Selected Views to clear constraints for the Label:

Now, we will put the Label at the top of the screen, having a 32 points margin from the top edge. Click the 'Add Constraints' tool, and set the top anchor constant to 32. Then click to 'Add 1 constraint':

So you see that the Label is anchored to the top edge of the screen with a 32 points gap:

Now, we will horizontally center the Label. Use the alignment tool to add the constraint:

Adding UITextField below UILabel
We now add the UITextField using the Object library (Command(⌘) + Shift + L). Look for text, and drag and drop TextField on the screen.

Now, let's center the TextField:

Then add the 16 points constraint to the top so that the TextField is anchored to the bottom of the Label having a 16 points gap.

For a TextField, you should give a user some hint of what kind of text the app is expecting. For example, we want to give the user a hint, "Put some text". So, we will use the 'Place holder' attribute in the right pane of the TextField to set it.

Now run the app.

You can see now, you can type something on the TextField.
Please note, you are using your computer keyboard to put the text inside. You can use the emulator (device) keyboard too. From the Simulator menu, click I/O -> Keyboard -> Toggle Software Keyboard.

Last updated
Was this helpful?