Getting what the user typed — iOS #7

Andy O'Sullivan
8 min readMar 2, 2017
icons from the awesome icons8.com

Pink cover image, loving it! Today we cover something basic but important — allowing the user to type in something and then using it to do something else.

Let’s get straight to it — start a new project in Xcode, a Single View application will do. Once open go the Main.storyboard, and search in the Object Library for a TextField.

Drag it two of them onto the main ViewController:

A TextField is an object that when the user taps on it, the keyboard will pop up and allow them to enter text. It’s for single lines of text — if you want a multi-line objcect, you can use a TextView instead; more on them later. Let’s make the TextFields wider, by dragging out the sides and repositioning them. We’ll also give them a background color of blue so they stand out:

probably should have used more pink so it matched

We can set Placeholders for the TextFields — this is text that appears in the field until the user starts typing; they’re intended to inform the user what information is expected.

For the first TextField, we’ll set a Placeholder of “Name”:

For the second, we’ll set a Placeholder of “Phone:

We can also set what type of keyboard will pop up when the user hits a TextField. We’ll lave the Name field as is, but we’ll set the Phone field to use the Keyboard Type of Phone Pad:

Run the app now to see the difference in keyboard when you hit the fields:

and

Ok, so the user can now type in a name and phone number — but we’ve no code to actually retrieve that information or do anything with it.

Let’s add a Button — I’ve resized it, given it a new background color, text color and changed the word “Button” to “Submit”:

We’ll also add in a Label underneath — we’ll jack up the Font size to 24.0 and we’ll resize it. We’ll also delete the “Label” text, so it’ll be blank for now:

Blank Label added

We’re going to use this label to display back what the user enters.

Ok, so we have our basic layout. We now need to add Outlets to the matching ViewController.swift file for the two TextFields and the Label and we need to add an Action for the Button.

So we open the Assistant Editor (via the button with the two little circles) and the ViewController.swift file should open beside the Storyboard:

Now Control-drag from the Name TextField to the ViewController file, making sure you “drop” the line inside the main curly brackets { and } but outside of any of the functions. This box will appear:

Type a meaningful Name in, here I choose “nameTextField” and I hit Connect:

resulting in the code:

@IBOutlet weak var nameTextField: UITextField!

being added:

Now do the same for the Phone TextField:

For the button, when we “drop” the Control-drag line, we select Action instead of Outlet. This will create an Action function for us to use — basically the function will be what is run when the user taps on the button:

I call it “onButtonClick” — but I could have called it anything. The code should now look like:

Finally, we add another Outlet for the Label:

Note that you can’t just copy & paste these Outlets and Actions into the file from here — they actually have to be linked to the objects in the Storyboard, so you have to do it the Control-drag way.

Ok, now let’s write the code to take in what the user types and display it back on screen.

First thing you need to do is add:

 , UITextFieldDelegate

like this:

class ViewController: UIViewController, UITextFieldDelegate {

This is known as “implementing a delegate”. What? Basically some objects that you use come with functions that you can use to do things with that objects. By “use” I mean that you actually write out the function definition and add any extra code that you need.

This is best explained by showing it in action. Add this delegate function to your code:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {}

This function textFieldShouldReturn is a delegate method that is provided to you to use. It is called everytime the user hits the “Enter” / “Return” key on the keyboard, when using a TextField. The textField paramater:

(_ textField: UITextField)

is the actual TextField that is being used.

Why would we use this function? We can use it to do things like:

  • move the user to the next TextField
  • dismiss the keyboard from the screen

You should see a red error mark beside the code:

This is because the function expects a Bool return type, and we haven’t done this yet — we haven’t written any code yet inside the function. Add this code so the function looks like:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTextField {
textField.resignFirstResponder()
phoneTextField.becomeFirstResponder()
}else{
phoneTextField.resignFirstResponder()
}
return true
}

This

if textField == nameTextField {

checks if the TextField that the user has hit Return inside, is the Name TextField. If it is then we run this code:

textField.resignFirstResponder()

which says “we’re finished with this TextField” and

phoneTextField.becomeFirstResponder()

which then moves the user to the Phone TextField.

If we run the app now, tap the Name TextField so the keyboard comes up, and then hit the “Return” key — nothing will happen! It’s because we’ve left out one step.

Add these two rows to the viewDidLoad function:

nameTextField.delegate = selfphoneTextField.delegate = self

so it looks like this:

This is basically saying that both TextFields will be using the TextField Delegate in this class. Ok, run the app now and tap the Name field, then hit the Return key. It should move to the Phone field, with the keyboard changing to the number pad:

Before we move on, let’s change the “Return” key to “Next”. In Xcode, select the Name TextField and in the Attributes Inspector, set Return Key to Next. Run the app again, tap Name and see how the keyboard has changed:

Amazing! Sort of! Did you note that the Phone keyboard doesn’t have a Return or Next key? It just has a back button instead, so the user can delete a number if entered incorrectly. How do we get rid of the keyboard then?

There’s a few ways of doing this, for now we’ll include code to dismiss it two ways:

  • if the user taps anywhere outside of the TextFields
  • if the user taps the Submit button

Add this code to the viewDidLoad function:

let tapRecogniser = UITapGestureRecognizer()
tapRecogniser.addTarget(self, action: #selector(self.viewTapped))
self.view.addGestureRecognizer(tapRecogniser)

What? Here we create a UITapGestureRecognizer — a class that we use to let us know when the user taps the screen.

The first line creates it as a variable called tapRecogniser:

let tapRecogniser = UITapGestureRecognizer()

the second adds a target to the recogniser. A target is the function that will be ran when the screen is tapped:

tapRecogniser.addTarget(self, action: #selector(self.viewTapped))

I’ve called it viewTapped — this doesn’t exist yet but will in a minute!

The third line then adds the recogniser to self.view — this is the main view of the ViewController, basically the “screen”:

self.view.addGestureRecognizer(tapRecogniser)

Ok, now we add the function viewTapped:

func viewTapped(){
self.view.endEditing(true)
}

This simply runs the command:

self.view.endEditing(true)

which dismisses the keyboard. Those pieces of code should look something like this:

Ok, almost there. Now let’s add code to the onButtonClick function we created earlier to:

  • dismiss the keyboard
  • print what the user entered on screen — by using the outputLabel Label we also created earlier.

Here’s the code:

@IBAction func onButtonClick(_ sender: Any) {
viewTapped()
let name: String = nameTextField.text!
let phone: String = phoneTextField.text!
outputLabel.text = " \(name) \(phone) "
}

The

viewTapped()

is just running our function again to dismiss the keyboard. Showing the beauty of functions — define once, use multiple times!

let name: String = nameTextField.text!
let phone: String = phoneTextField.text!

creates two new variables to store the values the user enters. The .text is how it’s done, that gets the actual information typed in. The ! at the end of text is called an optional. This basically says that nameTextField.text may have a value, but it also may not — as the user may not enter anything.

Finally,

outputLabel.text = " \(name) \(phone) "

changes our outputLabel to show the name, followed by the phone number.

How it works is we’ve created a String by using the double quotes:

" "

Inside the quotes we then use

\()

to include the value of a variable, here

\(name)

and

\(phone)

It’s a nice way of including variable values within Strings.

Note that we didn’t have to create those two variable, we could have instead just used this:

@IBAction func onButtonClick(_ sender: Any) {
viewTapped()
outputLabel.text = " \(nameTextField.text!) \(phoneTextField.text!) "
}

Ok, run the app and try it out! Enter some info, then hit Submit, it should appear on screen:

Great! One more thing — if you want to clear the two fields when you hit Submit, include this:

nameTextField.text = ""
phoneTextField.text = ""

e.g. (with some comments thrown in):

Try again:

Ok, that’s it, hopefully it all made sense. Any questions or comments, just let us know below!

If you liked this article, please hit the little heart button below! Thanks, Andy

--

--