Hi All, hope everyone is exploring/learning Swift. I have created a sample application which uses UIPickerView and UIDatePicker. I thought of sharing with you. Lets see what I did.
I have created a empty project and added a new swift file called "UIPickerViewDemoController" and a xib file "UIPickerViewDemo.xib".
I am going to add two text fields one for picker view and one for date picker.
Here is the complete initialisation code in viewDidLoad method :
I have created a empty project and added a new swift file called "UIPickerViewDemoController" and a xib file "UIPickerViewDemo.xib".
I am going to add two text fields one for picker view and one for date picker.
@IBOutlet var textField:UITextField
@IBOutlet var dateTextField:UITextField
Added a Picker View and Date Picker and created outlets for them.
@IBOutlet var pickerView:UIPickerView
@IBOutlet var datePicker:UIDatePicker
Have assigned pickers to inputView property of text fields
textField.inputView = pickerView
dateTextField.inputView = datePicker
Corresponding picker will be shown based up on the first responder status.
Here is how XIB look like :
Here is the complete initialisation code in viewDidLoad method :
@IBOutlet var pickerView:UIPickerView
@IBOutlet var textField:UITextField
@IBOutlet var datePicker:UIDatePicker
@IBOutlet var dateTextField:UITextField
var elements:Array<String>?
override func viewDidLoad()
{
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge.None
self.title = "Picker View"
textField.inputView = pickerView
elements = ["One","Two","Three","Five","Six","Seven","Eight","Nine","Ten"]
dateTextField.inputView = datePicker
}
Following are the delegate and datasource implementation for picker view :
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int
{
return 1;
}
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int
{
return elements!.count;
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String
{
return elements![row]
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
textField.text = elements![row]
}
Following is the valueChanged selector for date picker :
@IBAction func dateValueChanged(sender:UIDatePicker)
{
dateTextField.text = sender.date.description
}
Here is the output :
You can download source code here