Advertise

Sunday, March 5, 2017

iOS: Picker View and Date Picker View integration with TextField in Swift 3.0



While you are creating a form like user profile you need to add some fields and among that you need to give user a action to choose between them. For Gender, Country, State, Date fields Picker View is a best option to fulfil our requirement. Picker View comes in picture because if you have set date field and user enters his name then? How you evaluate user enters proper date ? Same way if you set country name and user enters state name then? How you identify the country name is correct or not? In global application it will store in central database and reflect in every platform, so it reflects wrong information everywhere. To prevent this issue, you can give user a bunch of options from where he/she can choose.

Due to, screen size limitation, you can add picker view as a fade in when required and fade out after selection. In this tutorial, we will integrate Picker View and Date Picker View similarly as shown above image.

So, Let's start coding instead of doing stories:

First, Create a project named "PickerView Demo" or whatever you like and create a view as shown below. You just need to add two labels and two TextFields.




Give textfield outlet to it's Controller swift file:

 @IBOutlet weak var countryNameField : UITextField!
 @IBOutlet weak var dateField: UITextField!


We are going to PickerView to select country name and choose Date PickerView to select Date. For, Country name, first we should have array with Country name list. So, Add below code just below above code.

let countryArray = ["India","United States", "United Kingdom","Canada","Australia","UAE","Russia","China"]

Then, add two controller PickerView and DatePicker:

@IBOutlet var countryPicker : UIPickerView!
@IBOutlet var datePicker : UIDatePicker!

In both picker view, we need to initialise component and give them a array which is used to display and also connect it with text fields. This will done with simple 3-4 line code. It is not a rocket science. Just copy and paste below code into viewDidLoad() method.

        // Country PickerView
        countryPicker = UIPickerView()
        countryPicker.tag = 1
        countryPicker.delegate = self
        countryPicker.dataSource = self
        countryNameField.inputView = countryPicker
        countryNameField.text = countryArray[0]
        
        //Date Picker
        datePicker = UIDatePicker()
        datePicker.tag = 100
        datePicker.datePickerMode = UIDatePickerMode.date
        datePicker.addTarget(self, action: #selector(self.setDate(_sender:)), for: .valueChanged)
        datePicker.timeZone = TimeZone.current
        dateField.inputView = datePicker

Above code easily understandable by you and no need to describe... I guess. Now, move on to further step. as, above code we are defined setDate(_sender:) method in DatePicker. So, we need to define it and add code for display user selected date into dateField.

func setDate(_sender : UIDatePicker){
        let dateFormatter: DateFormatter = DateFormatter()
        // Set date format
        dateFormatter.dateFormat = "MM/dd/yyyy"
        // Apply date format
        let selectedDate: String = dateFormatter.string(from: _sender.date)
        print("Selected value \(selectedDate)")
        if(_sender.tag == 100){
            dateField.text = "\(selectedDate)"
        }
        self.view.endEditing(true)
    }

Before, going to next step we need to add delegate methods for UIPickerView: UIPickerViewDelegate and UIPickerViewDataSource. Change your Class name code as below:

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource

Now, Final step is to integrate these delegate methods as below:

    //MARK:- PickerView Delegate
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return countryArray[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return countryArray.count
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        if(pickerView.tag == 1){
            countryNameField.text = countryArray[row]
            self.view.endEditing(true)
        }
    }

It is very simple code and understandable by anyone. We just define array into pickerView and when user select and row it will print those value into textField. self.view.endEditing(true) is used for disable PickerView.

Download Full Source Code






1 comment:

  1. Your work is very engaging! Amazing piece and is worth reading and sharing. Hoping for more of this kind of work of yours author. Meanwhile. If you are interested and looking for ios developerFeel free to check and visit our site. Thank you and Godbless!

    ReplyDelete