I'm trying to delete the elements of an pickerView using a UIButton, but after 3 consecutively deleted elements I get the error (Index out of Range).
Sorry for my bad english I am still young and live in Germany :D
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var textFiled: UITextField!
@IBOutlet weak var pickerView: UIPickerView!
var Array = ["Blue", "Green", "Red", "White", "Grey"]
var indexOfPicker = Int()
override func viewDidLoad() {
super.viewDidLoad()
pickerView.dataSource = self
pickerView.delegate = self
}
@IBAction func minusButton(_ sender: UIButton) {
if Array.count != 0 {
Array.remove(at: indexOfPicker)
pickerView.reloadAllComponents()
}
}
@IBAction func plusButton(_ sender: UIButton) {
if textFiled.text != "" {
Array.append(textFiled.text!)
pickerView.reloadAllComponents()
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Array.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Array[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
indexOfPicker = row
}
}
Thanks for any help!
Just Replace your function
With
Issue
While you remove an element from array index was not getting updated as
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
is only called when you change value in picker When Interactedbut while reloading you need to update index thus,
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int)
is called everytime when picker is reloaded which update your selected index when you reload or update arrayWorking Output