Using UIKit style in Swift, iPhone app development, 05 Choosing desired items using Picker View

1. Introduction

Swift is a modern programming language used for developing applications in the Apple ecosystem. With its fast, safe, and modern syntax, Swift plays a crucial role in iOS application development. UIKit is a framework for constructing and managing user interfaces, providing various UI components.

In this blog, we will explore one of the components of UIKit, the Picker View. The Picker View is a UI element that provides a selection of options to the user and allows easy reflection of the selected value. For example, it is useful for date pickers or selecting items from a list. We will learn how to create and use a Picker View with the Swift language.

2. What is a Picker View?

A Picker View is a view that allows the user to select from multiple items. It typically appears as a scrollable list, where users can scroll with their finger to make a selection. It offers similar functionality to Android’s Spinner or iOS’s UIAlertController but provides a more intuitive and user-friendly interface.

iOS’s Picker View has two basic types.

  • UIPickerView: It generally creates a 2D selector that allows items to be selected by scrolling vertically.
  • UIDatePicker: A special Picker for date and time selection, helping users to choose more specific dates and times.

3. Basic Structure of UIPickerView

UIPickerView operates similarly to UITableView, but each item displays important values for selection. To use UIPickerView, several protocols need to be implemented, following the data source protocol and delegate.


            class MyViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
                var pickerView: UIPickerView!
                var items: [String] = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
                
                override func viewDidLoad() {
                    super.viewDidLoad()
                    
                    pickerView = UIPickerView()
                    pickerView.dataSource = self
                    pickerView.delegate = self
                    
                    view.addSubview(pickerView)
                }

                // UIPickerView DataSource Methods
                func numberOfComponents(in pickerView: UIPickerView) -> Int {
                    return 1
                }

                func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
                    return items.count
                }
            }
            

4. Configuring UIPickerView and Displaying Items

The items to be displayed in the UIPickerView are stored in the ‘items’ array. The ‘numberOfComponents’ method returns the number of columns in the Picker View, and the ‘numberOfRowsInComponent’ method returns the number of items in each column.

Now, to display each item, we need to implement the pickerView(_:titleForRow:forComponent:) method. This method provides the title of the item to be displayed in each row of the Picker View.


            func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
                return items[row]
            }
            

5. Handling Item Selection

When a user selects an item from the UIPickerView, actions can be taken based on the selected value. To retrieve the selected item, we implement the pickerView(_:didSelectRow:inComponent:) method.


            func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
                let selectedItem = items[row]
                // Logic to handle the selected item
                print("Selected item: \(selectedItem)")
            }
            

6. UI Customization

The Picker View is provided in its basic form, but it can be customized in various ways. For instance, custom views can be provided for each item. To do this, we use the pickerView(_:viewForRow:forComponent:reusing:) method.


            func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
                let label = UILabel()
                label.text = items[row]
                label.textAlignment = .center
                // Additional styling
                return label
            }
            

7. Using UIDatePicker

UIDatePicker is a picker that can be used to set specific dates and times. UIDatePicker supports various styles when created and can be used in date or time format. It can be simply utilized as shown in the code example below.


            @IBOutlet weak var datePicker: UIDatePicker!

            override func viewDidLoad() {
                super.viewDidLoad()

                // Configuring UIDatePicker
                datePicker.datePickerMode = .date
            }

            @IBAction func dateChanged(_ sender: UIDatePicker) {
                let selectedDate = sender.date
                // Logic to handle the selected date
                print("Selected date: \(selectedDate)")
            }
            

8. Integrating Picker View into a Real App

Now we will demonstrate how to set up UIPickerView and UIDatePicker and integrate them into a real application without omitting any steps. Based on the view controller we have created, selected items and dates can be easily reflected or saved to other UI elements.

For example, here is a code snippet that displays the selected fruit name on a UILabel.


            @IBOutlet weak var selectedFruitLabel: UILabel!
            
            func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
                let selectedItem = items[row]
                selectedFruitLabel.text = "Selected fruit: \(selectedItem)"
            }
            

9. Conclusion

In this post, we learned how to implement UIPickerView and UIDatePicker using Swift and UIKit. We learned how to build a user-friendly interface and control the app’s behavior based on selected items.

The Picker View is a very useful tool that enriches the user experience of the app and helps users easily select the necessary information. It can be beneficial in various scenarios, so we encourage you to customize and implement it in a way that fits your application.