3.3.1. Send data back from Screen 2 to Screen 1: UIPickerView

Now let's open the second screen (ShowViewController). We are going to set up our PickerView moodPicker now. Let's define an array of Strings having three moods: "Happy," "Meh," and "Sad."

// moods for moodPicker...
let moods: [String] = ["Happy", "Meh", "Sad"] 

Also, let's declare a variable that keeps the selected mode:

Now it's time to set up the PickerView. To activate a PickerView, the class ShowViewController needs to adopt two Protocols: UIPickerViewDelegate, and UIPickerViewDataSource. UIPickerViewDelegate is the protocol to enable user interactions with the PickerView, and UIPickerViewDataSource is the protocol to access data to display on PickerView.

You can adopt it in two ways. The first way is the way we have seen in our Swift notes:

Or we can separate the code block from the class to make our code more readable by using extension keyword:

The keyword extension allows you to write code inside the same context of a class. You are writing code literally inside a class if you use an extension.

We will choose the second option, where we can keep the code separated. So, let's implement or adopt the methods in the protocols and define them. You need to write code for three methods to properly set up the moodPicker:

Here, numberOfComponents() method expects you to return the number of columns in PickerView. In our moodPicker we only have one column, so we will return 1. (There could be scenarios with multiple components, like a date picker).

You see, there are two methods named pickerView(), it might get you confused at first glance, but really they are used as overridden methods for the protocols. The most important parts are numberOfRowsInComponent and titleForRow parameters.

The first pickerView() method with numberOfRowsInComponent should return the number of rows in the current component/column. We have to populate the Strings in the moods array. So, we return moods.count.

The second pickerView() method with titleForRow should return the title we want to set for the selected row. Here, we need to show the Strings in the moods array, each mood in each row. So we return moods[row]. Before we return, we update selectedMood variable's value to the corresponding String to the currently selected row, moods[row].

Now, two more important tasks are yet to be done. We have to show the moodPicker the class where it can fetch the data from and enable user interaction. Add the following two lines of codes, in setupMoodPicker():

We are saying for enabling the user interactions (delegate), and as the data source moodPicker should use the ShowViewController class's current instance.

Now so far, the code files look like the following:

Last updated

Was this helpful?