Still pretty new to swift, I was having some trouble passing updated data into the pickerview. I'm receiving the "index out of range" error. I have a suspicion that the uipickerview is seeing the empty array, even though the arrays are getting updated. Any help is much appreciated.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var nameDisplay: UILabel!
@IBOutlet weak var ageDisplay: UILabel!
@IBOutlet weak var emailDisplay: UILabel!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var txtfirstName: UITextField!
@IBOutlet weak var txtAge: UITextField!
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var lblValidationMessage: UILabel!
var ages = [Int]()
var emailAddresses = [String]()
var firstNames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// lblValidationMessage.isHidden = true
// Do any additional setup after loading the view.
//links txtAge to the UITextField class, which gives access to func textfield
txtAge?.delegate = self
pickerView?.dataSource = self
pickerView?.delegate = self
}
// restricts the values possible to input in txtAge.text
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = "1234567890"
let allowedCharcterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharcterSet = CharacterSet(charactersIn: string)
return allowedCharcterSet.isSuperset(of: typedCharcterSet)
}
@IBAction func addUserButton(_ sender: UIButton) {
//validation of data in the text boxes
lblValidationMessage.isHidden = true
if let firstName = txtfirstName.text, firstName == "" {
lblValidationMessage.isHidden = false
lblValidationMessage.text = "Enter Your Name"
return
}
if let age = txtAge.text, age == "" {
lblValidationMessage.isHidden = false
lblValidationMessage.text = "Please enter a numerical age"
return
}
if let email = txtEmail.text, email.isEmpty {
lblValidationMessage.isHidden = false
lblValidationMessage.text = "Please enter an email address"
return
}
//MARK: Adds entries to the 3 arrays
firstNames.append(txtfirstName.text!)
//Converts string to int, the age array requires INT
let age:Int! = Int(txtAge.text!)
ages.append(age)
emailAddresses.append(txtEmail.text!)
txtfirstName.text = ""
txtAge.text = ""
txtEmail.text = ""
//Brings focus back to First Name text field
txtfirstName.becomeFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return firstNames.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
nameDisplay.text = firstNames[row]
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return firstNames[row]
}
}