How to set data for multiple UIpickerviews in Swift? - swift

I have uiviewcontroller with uitextfields, when users tap on the textfields uipickerview appears as shown in the attachment.
How can I make multiple uipickerview? For example, when the user tap on the countries textfields a pickerview shows up with countries array data and when users tap on the gender textfields uipickerview shows the genders array data and so on. I tried but only able to do it for one array which is countries as shown in my code. would appreciate if you could show me how to do it for the rest of my uitextfields.
import UIKit
class testVC: UIViewController,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource {
var countries = ["USA","UK","Spain" ]
var gender = ["Male","Female","Both"]
var language = ["English","French","Spanish","Other"]
override func viewDidLoad() {
super.viewDidLoad()
var pickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 100))
pickerView.backgroundColor = .whiteColor()
pickerView.showsSelectionIndicator = true
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
pickerView.delegate = self
pickerView.dataSource = self
[![enter image description here][1]][1]
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "canclePicker")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
genderTxt.inputView = pickerView
genderTxt.inputAccessoryView = toolBar
countriesTxt.inputView = pickerView
countriesTxt.inputAccessoryView = toolBar
categoriesTxt.inputView = pickerView
categoriesTxt.inputAccessoryView = toolBar
startDateTxt.inputView = pickerView
startDateTxt.inputAccessoryView = toolBar
endDateTxt.inputView = pickerView
endDateTxt.inputAccessoryView = toolBar
languageTxt.inputView = pickerView
languageTxt.inputAccessoryView = toolBar
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return countries.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return countries[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var itemselected = countries[row]
countriesTxt.text = itemselected
}

You don't need multiple UIPickerView. Instead you need to set picker view data source based on first responder text view. Also you should implement textFieldShouldBeginEditing delegate method to reload content of picker view by calling its reloadAllComponents method
var pickerView : UIPickerView!
override func viewDidLoad() {
self.pickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 100))
NSNotificationCenter.defaultCenter().addObserver(self, selector: ("updatePicker"), name: UITextFieldTextDidBeginEditingNotification, object: nil)
}
func updatePicker(){
self.pickerView.reloadAllComponents()
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if countriesTxt.isFirstResponder(){
return countries.count
}else if genderTxt.isFirstResponder(){
return gender.count
}
// continue this way and implement all cases
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if countriesTxt.isFirstResponder(){
return countries[row]
}else if genderTxt.isFirstResponder(){
return gender[row]
}
// continue this way and implement all cases
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if countriesTxt.isFirstResponder(){
var itemselected = countries[row]
countriesTxt.text = itemselected
}else if genderTxt.isFirstResponder(){
var itemselected = gender[row]
genderTxt.text = itemselected
}
// ...
}

You should add booleans to know what kind of data you want to pick, then you should check these booleans to know the array you want to take the data from, and when you open the picker view assign the correct values:
import UIKit
class testVC: UIViewController,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource {
var countries = ["USA","UK","Spain" ]
var gender = ["Male","Female","Both"]
var language = ["English","French","Spanish","Other"]
var countriesFlag = true
var genderFlag = false
var languageFlag = false
override func viewDidLoad() {
super.viewDidLoad()
var pickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 100))
pickerView.backgroundColor = .whiteColor()
pickerView.showsSelectionIndicator = true
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
pickerView.delegate = self
pickerView.dataSource = self
[![enter image description here][1]][1]
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "canclePicker")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
genderTxt.inputView = pickerView
genderTxt.inputAccessoryView = toolBar
countriesTxt.inputView = pickerView
countriesTxt.inputAccessoryView = toolBar
categoriesTxt.inputView = pickerView
categoriesTxt.inputAccessoryView = toolBar
startDateTxt.inputView = pickerView
startDateTxt.inputAccessoryView = toolBar
endDateTxt.inputView = pickerView
endDateTxt.inputAccessoryView = toolBar
languageTxt.inputView = pickerView
languageTxt.inputAccessoryView = toolBar
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
//Add this delegate to know the clicked textview
textViewDidBeginEditing(textView: UITextView) {
if textView == countriesTxt {
countriesFlag = true
genderFlag = false
languageFlag = false
} else if textView == genderTxt {
countriesFlag = false
genderFlag = true
languageFlag = false
} else {
countriesFlag = false
genderFlag = false
languageFlag = true
}
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if countriesFlag {
return countries.count
} else if genderFlag {
return gender.count
} else {
return language.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if countriesFlag {
return countries[row]
} else if genderFlag {
return gender[row]
} else {
return language[row]
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if countriesFlag {
var itemselected = countries[row]
countriesTxt.text = itemselected
} else if genderFlag {
var itemselected = gender[row]
genderTxt.text = itemselected
} else {
var itemselected = language[row]
languageTxt.text = itemselected
}
}
}

Related

Pickerview is showing empty on second click in the textfield, adn when i press Done or Cancel the App crashes

var gender = ["MALE","FEMALE", "Other"]
var genderPicker: UIPickerView! = UIPickerView()
// On the first click in the textfield the gender pickerview works fine, but if i press out and then i press again in the gender textfield the picker appears empty.
// And when i press either cancel or Done to dismiss the picker the app crashes with the below error
Unrecognized selector sent to instanceā€ in swift
override func viewDidLoad() {
super.viewDidLoad()
tableViewHeight.constant = screenHeight * 0.7
// Do any additional setup after loading the view.
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.systemBlue
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: "donePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: "donePicker")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
genderTxtField.delegate = self
genderPicker!.delegate = self
genderPicker!.dataSource = self
genderTxtField.inputAccessoryView = toolBar
self.genderTxtField.inputView = genderPicker
}
func donePicker() {
genderTxtField.resignFirstResponder()
}
// Delegates Methods
extension InsuranceMethodsSemiViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
genderPicker.isHidden = false
genderTxtField.inputView = genderPicker;
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
genderPicker.isHidden = true
}
}
extension InsuranceMethodsSemiViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return gender[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
genderTxtField.text = gender[row]
self.view.endEditing(true)
pickerView.isHidden = true
}
}
extension InsuranceMethodsSemiViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return gender.count
}
}
1- Add _
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
genderPicker.isHidden = false
genderTxtField.inputView = genderPicker;
return true
}
2- Change action to #selector(donePicker)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(donePicker))
With
#objc func donePicker() {

Two UIPickerViews in one ViewController

Two PickerViews selectTypeOfWorkChoices & selectLocationChoices do not appear correctly.
A function dismissPickerView() seems working well. However, another function "createPickerView()" has some problems. Although UIpickerviews appear, I cannot see the choices in UIPickerViews and I don't know why.
Could anyone help me figure out what's wrong with my code, please??
#IBOutlet weak var selectTypeOfWorkChoices: UIPickerView!
#IBOutlet weak var selectLocationChoices: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
createPickerView()
dismissPickerView()
}
var typeOfWork = ["--", "a", "b", "c"]
var location = ["--", "A", "B", "C"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var countrows : Int = typeOfWork.count
if pickerView == selectLocationChoices {
countrows = self.location.count
}
return countrows
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == selectTypeOfWorkChoices {
let titleRow = typeOfWork[row]
return titleRow
}
else if pickerView == selectLocationChoices {
let titleRow = location[row]
return titleRow
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == selectTypeOfWorkChoices {
selectedPriority = typeOfWork[row]
selectTypeOfWork.text = selectedPriority
self.selectTypeOfWork.text = self.typeOfWork[row]
}
else if pickerView == selectLocationChoices {
locationSelectedPriority = location[row]
selectLocation.text = locationSelectedPriority
self.selectLocation.text = self.location[row]
}
}
var selectedPriority : String?
var locationSelectedPriority : String?
func createPickerView() {
let pickerView = UIPickerView()
pickerView.delegate = self
self.selectTypeOfWorkChoices.delegate = self
self.selectTypeOfWorkChoices.dataSource = self
self.selectLocationChoices.delegate = self
self.selectLocationChoices.dataSource = self
selectTypeOfWork.inputView = selectTypeOfWorkChoices
selectLocation.inputView = selectLocationChoices
}
#objc func dismissPickerView() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title:"Done", style: .plain, target: self, action: #selector(self.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
selectTypeOfWork.inputAccessoryView = toolBar
selectLocation.inputAccessoryView = toolBar
}
#objc func dismissKeyboard () {
view.endEditing(true)
}
Reload the picker view after assigning an input view to your text field.
func createPickerView() {
let pickerView = UIPickerView()
pickerView.delegate = self
self.selectTypeOfWorkChoices.delegate = self
self.selectTypeOfWorkChoices.dataSource = self
self.selectLocationChoices.delegate = self
self.selectLocationChoices.dataSource = self
selectTypeOfWork.inputView = selectTypeOfWorkChoices
selectLocation.inputView = selectLocationChoices
//Reload Pickerview
self.selectTypeOfWorkChoices.reloadAllComponents()
self.selectLocationChoices.reloadAllComponents()
}

Add a Function into an Alert

I'm trying to create a alert that makes a function when recieve's the OK.
what my app does is that it takes product information via an pickerView and it gives out ID numbers. but first I want to make sure if the product that the user has given is assured.
Here's my code:
import UIKit
import Foundation
struct Service {
var id1: Int
var title: String
}
struct Brand {
var id2: Int
var title: String
ko}
class PickerTextField: UITextField,UIPickerViewDelegate,UIPickerViewDataSource {
let pickerView = UIPickerView()
var itemList = [Service]()
var selectedItem:Service?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
#objc func textEdited(_ sender:PickerTextField)
{
self.text = itemList[pickerView.selectedRow(inComponent: 0)].title
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.tintColor = UIColor.clear
self.addTarget(self, action: #selector(textEdited(_:)), for: .editingChanged)
pickerView.showsSelectionIndicator = true
pickerView.delegate = self
pickerView.dataSource = self
self.inputView = pickerView
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = .black
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneBtnAction(_:)))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(doneBtnAction(_:)))
toolBar.items = [cancelButton, spaceButton, doneButton]
self.inputAccessoryView = toolBar
}
#objc func doneBtnAction(_ sender:UIBarButtonItem) {
resignFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return itemList.count
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let title = itemList[row].title
return NSAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor:UIColor.black])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedItem = itemList[row]
self.text = itemList[row].title
}
}
class PickerTextField2: UITextField,UIPickerViewDelegate,UIPickerViewDataSource {
let pickerView2 = UIPickerView()
var itemList2 = [Brand]()
var selectedItem2:Brand?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
#objc func textEdited(_ sender:PickerTextField)
{
self.text = itemList2[pickerView2.selectedRow(inComponent: 0)].title
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.tintColor = UIColor.clear
self.addTarget(self, action: #selector(textEdited(_:)), for: .editingChanged)
pickerView2.showsSelectionIndicator = true
pickerView2.delegate = self
pickerView2.dataSource = self
self.inputView = pickerView2
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = .black
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneBtnAction(_:)))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(doneBtnAction(_:)))
toolBar.items = [cancelButton, spaceButton, doneButton]
self.inputAccessoryView = toolBar
}
#objc func doneBtnAction(_ sender:UIBarButtonItem) {
resignFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return itemList2.count
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let title = itemList2[row].title
return NSAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor:UIColor.black])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedItem2 = itemList2[row]
self.text = itemList2[row].title
}
}
class ViewController: UIViewController {
#IBOutlet weak var servicesField: PickerTextField!
#IBOutlet weak var brandsField: PickerTextField2!
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
servicesField.itemList = [Service(id1: 1, title: "Mobile Phone")]
brandsField.itemList2 = [Brand(id2: 01, title: "Apple")]
}
#IBAction func reCheckButton(_ sender: Any) {
//When pressed: pop up an alert to make sure it's 'Mobile Phone Apple?"
}
(read the comment I added into the IBAction above)
and when OK is pressed I want this func to happen:
func reCheck() {
if let servicesFieldId = servicesField.selectedItem?.id1, let brandsFieldId = brandsField.selectedItem2?.id2 {
label.text = String(servicesFieldId) + String(format: "%02d%02d", brandsFieldId})
}
Now I've searched around on the Stackoverflow but I couldn't find the right code in the similar questions.
How can I code this specified UIAlert?
Thanks.
You Need After user confirm message you call function
You can create Alert Extension to UIViewController
extension UIViewController {
func createAlert (title:String, message:String, completion:#escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
And inside your Action
#IBAction func reCheckButton(_ sender: Any) {
self.createAlert(title: "title", message: "Mesage") { (isOk) in
if isOk {
if let servicesFieldId = servicesField.selectedItem?.id1, let brandsFieldId = brandsField.selectedItem2?.id2 {
label.text = String(servicesFieldId) + String(format: "%02d%02d", brandsFieldId})
}
}
}

Select first or any row with done button in UIPickerView and UIDatePicker for Swift

I have a ViewController with 4 UITextFields. First 3 are populated by their own UIPickerViews and the 4th is populated by a UIDatePicker.
I want a done button to be able to select the first row of each picker or select whichever row is selected if not the first.
Below is the code that works for the first UIPicker. Got it from Selecting first row in UIPickerView issue.
func doneButton(sender: AnyObject) {
let row = pickerView1.selectedRow(inComponent: 0);
pickerView(pickerView1, didSelectRow: row, inComponent:0)
view.endEditing(true)
}
How do I enable the done button to work independently for all 4 pickers?
Here is the full code.
Any help much appreciated.
var selectedItemsArray = [String]()
class RunInputViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate{
var pickerView1 = UIPickerView()
var pickerView2 = UIPickerView()
var pickerView3 = UIPickerView()
var pickerView4 = UIDatePicker()
#IBOutlet weak var runTypeTextField: UITextField!
#IBOutlet var runTextField: UITextField!
#IBOutlet var snowTypeTextField: UITextField!
#IBOutlet var dateTextField: UITextField!
#IBAction func saveRun(_ sender: Any){
if (runTypeTextField.text != ""){
runFeedList.append(runTypeTextField.text!)
runTypeTextField.text = ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
createToolbar()
pickerView1 = UIPickerView()
pickerView2 = UIPickerView()
pickerView3 = UIPickerView()
pickerView4 = UIDatePicker()
pickerView1.delegate = self
pickerView1.dataSource = self
pickerView2.delegate = self
pickerView2.dataSource = self
pickerView3.delegate = self
pickerView3.dataSource = self
pickerView1.tag = 0
pickerView2.tag = 1
pickerView3.tag = 2
pickerView4.tag = 3
self.runTypeTextField.inputView = self.pickerView1;
self.runTextField.inputView = self.pickerView2;
self.snowTypeTextField.inputView = self.pickerView3;
self.dateTextField.inputView = self.pickerView4;
pickerView4.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
pickerView4.datePickerMode = UIDatePickerMode.time
//let currentDate = NSDate()
//pickerView4.minimumDate = currentDate as Date
//pickerView4.date = currentDate as Date
pickerView4.timeZone = NSTimeZone.local
pickerView4.minuteInterval = 5
}
func createToolbar() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
//Customizations
toolBar.barTintColor = .black
toolBar.tintColor = .white
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(RunInputViewController.doneButton(sender:)))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
runTypeTextField.inputAccessoryView = toolBar
runTextField.inputAccessoryView = toolBar
snowTypeTextField.inputAccessoryView = toolBar
dateTextField.inputAccessoryView = toolBar
}
func doneButton(sender: AnyObject) {
let row = pickerView1.selectedRow(inComponent: 0);
pickerView(pickerView1, didSelectRow: row, inComponent:0)
view.endEditing(true)
}
func dismissKeyboard() {
view.endEditing(true)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
pickerView4.datePickerMode = UIDatePickerMode.time
dateTextField.text = dateFormatter.string(from: sender.date)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return runType.count
} else if pickerView.tag == 1 {
return selectedItemsArray.count
} else if pickerView.tag == 2 {
return snowType.count
}
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0 {
return runType[row]
} else if pickerView.tag == 1 {
return selectedItemsArray[row]
} else if pickerView.tag == 2 {
return snowType[row]
}
return ""
}
var selectedRow: Int = 0
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedRow = row
if pickerView == pickerView1 {
runTypeTextField.text = runType[row]
switch row {
case 0:
selectedItemsArray = RunGreen
case 1:
selectedItemsArray = RunBlue
case 2:
selectedItemsArray = RunBlack
case 3:
selectedItemsArray = RunDoubleBlack
default:
selectedItemsArray = []
}
pickerView2.reloadAllComponents()
} else if pickerView == pickerView2 {
let item = selectedItemsArray[row]
if selectedItemsArray == rRunGreen {
runTextField.text = item
} else if selectedItemsArray == RunBlue {
runTextField.text = item
} else if selectedItemsArray == rRunBlack {
runTextField.text = item
} else if selectedItemsArray == RunDoubleBlack {
runTextField.text = item
}
}
if pickerView.tag == 2 {
snowTypeTextField.text = snowType[row]
}
}
}
check this code working with two picker with different array inputs and one Date picker
import UIKit
class PickerViewController: UIViewController,UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var pickerVieww: UIPickerView!
#IBOutlet weak var DateePicker: UIDatePicker!
#IBOutlet weak var newPickr: UIPickerView!
var viewControllerArray = [String]()
var viewControllerArray1 = [String]()
var value = Int()
var value1 = Int()
override func viewDidLoad() {
super.viewDidLoad()
pickerVieww.delegate = self
pickerVieww.dataSource = self
newPickr.delegate = self
newPickr.dataSource = self
pickerVieww.tag = 1
newPickr.tag = 2
viewControllerArray = ["controller1","controller2","controller3"]
viewControllerArray1 = ["controller4","controller5","controller6","controller7"]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == pickerVieww
{
return viewControllerArray.count
}
else if pickerView == newPickr
{
return viewControllerArray1.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == pickerVieww
{
return viewControllerArray[row]
}
else if pickerView == newPickr
{
return viewControllerArray1[row]
}
return ""
}
func pickerView(_ pickerView: UIPickerView,didSelectRow row: Int,inComponent component: Int)
{
}
#IBAction func DoneButton(_ sender: Any) {
let row = pickerVieww.selectedRow(inComponent: 0);
print("pickervieww value: \(row)")
let row1 = newPickr.selectedRow(inComponent: 0);
print("newpicker value: \(row1)")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
let date:String = dateFormatter.string(from: DateePicker.date)
print("date: \(date)")
}
}
Console output on a button Action
So I figured out the answer to my own question. I had tried to create separate code for each UITextFiled and UIPickerView as suggested by #user3589771 but I was missing something.
My original code had
runTypeTextField.inputAccessoryView = toolBar
runTextField.inputAccessoryView = toolBar
snowTypeTextField.inputAccessoryView = toolBar
dateTextField.inputAccessoryView = toolBar
but once I separated the .inputAccessoryView for each UITextField is all came together.
I finally sorted it out and the answer is below.
func createToolbar() {
// Tool bar for 1st UIPickerView
let toolBar1 = UIToolbar()
toolBar1.sizeToFit()
toolBar1.barTintColor = .black
toolBar1.tintColor = .white
let doneButton1 = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(RunInputViewController.doneButton1(sender:)))
toolBar1.setItems([doneButton1], animated: false)
toolBar1.isUserInteractionEnabled = true
runTypeTextField.inputAccessoryView = toolBar1
// Tool bar for 2nd UIPickerView
let toolBar2 = UIToolbar()
toolBar2.sizeToFit()
toolBar2.barTintColor = .black
toolBar2.tintColor = .white
let doneButton2 = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(RunInputViewController.doneButton2(sender:)))
toolBar2.setItems([doneButton2], animated: false)
toolBar2.isUserInteractionEnabled = true
runTextField.inputAccessoryView = toolBar2
// Tool bar for 3rd UIPickerView
let toolBar3 = UIToolbar()
toolBar3.sizeToFit()
toolBar3.barTintColor = .black
toolBar3.tintColor = .white
let doneButton3 = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(RunInputViewController.doneButton3(sender:)))
toolBar3.setItems([doneButton3], animated: false)
toolBar3.isUserInteractionEnabled = true
snowTypeTextField.inputAccessoryView = toolBar3
// Tool bar for UIDatePicker
let toolBar4 = UIToolbar()
toolBar4.sizeToFit()
toolBar4.barTintColor = .black
toolBar4.tintColor = .white
let doneButton4 = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(RunInputViewController.doneButton4))
toolBar4.setItems([doneButton4], animated: false)
toolBar4.isUserInteractionEnabled = true
dateTextField.inputAccessoryView = toolBar4
}
// Done button for 1st UIPickerView
func doneButton1(sender: AnyObject) {
let row1 = pickerView1.selectedRow(inComponent: 0);
pickerView(pickerView1, didSelectRow: row1, inComponent:0)
view.endEditing(true)
}
// Done button for 2nd UIPickerView
func doneButton2(sender: AnyObject) {
let row2 = pickerView2.selectedRow(inComponent: 0);
pickerView(pickerView2, didSelectRow: row2, inComponent:0)
view.endEditing(true)
}
// Done button for 3rd UIPickerView
func doneButton3(sender: AnyObject) {
let row3 = pickerView3.selectedRow(inComponent: 0);
pickerView(pickerView3, didSelectRow: row3, inComponent:0)
view.endEditing(true)
}
// Done button for UIDatePicker
func doneButton4(){
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
dateTextField.text = formatter.string(from: pickerView4.date)
self.view.endEditing(true)
}

How to set tag for picker view programmatically?

I am Building iOS App using swift.
In my viewcontroller i need 6 picker views.
Previously i created PickerViews using IB.
Now i think to do it in programmatically,because i want to implement Done and Cancel Button.
I created a sample project and checked.There i am getting the pickerview displayed.
But in my original app its not working.
May be number of pickers is large.
And Every time tag value of picker is showing zero.
I tried to set tag value like this,
pickerView.tag == 2
This is code for creating Picker
func createPicker1(){
var pickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
pickerView.tag == 2
pickerView.backgroundColor = .greenColor()
pickerView.delegate = self
pickerView.dataSource = self
pickerView.showsSelectionIndicator = true
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
println(pickerView.tag)
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker1")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "canclePicker1")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
pwrd.inputView = pickerView
pwrd.inputAccessoryView = toolBar
}
These are my Picker Methods.
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (pickerView.tag == 0){
return categories.count
}
else
{
return skillNeeded.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if (pickerView.tag == 0) {
return categories[row]
}
else{
return skillNeeded[row]
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if (pickerView.tag == 0) {
user.text = categories[row]
}
else {
pwrd.text = skillNeeded[row]
}
}
Thanks.Your help will be appreciated.
You don't set values with ==
try pickerView.tag = 2