How to implement a Picker View on text field tap?
I have build a simple one screen application with a text field. The end goal is for the user to touch on the text field where they will be given with a list of options to choose from, the currently chosen option will appear in the text field.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource{
// MARK: - @IBOutlet
@IBOutlet weak var oSelectedPickerTextField: UITextField!
// MARK: - Variables
var pickerView = UIPickerView()
var pickerArray = ["abc","cde","fgi","jkl","mno","pqi"]
// MARK: - ViewController LifeCycle's override func viewDidLoad() {
super.viewDidLoad() self.loadItem()
}
// MARK: - Custom Func func loadItem(){
self.oSelectedPickerTextField.delegate =
self self.oSelectedPickerTextField.layer.cornerRadius = 10
self.oSelectedPickerTextField.layer.borderColor = UIColor.black.cgColor;
self.oSelectedPickerTextField.layer.borderWidth = 1.5
self.pickerView.delegate = self
self.pickerView.dataSource = self
self.oSelectedPickerTextField.inputView = self.pickerView
}
/// Delegate Method
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return self.pickerArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return self.pickerArray[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
self.oSelectedPickerTextField.text = "\(self.pickerArray[row])"
}
}