How can I delete the selected location in a pickerView using a UIButton?

863 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

Just Replace your function

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return Array[row]
}

With

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        indexOfPicker = row
        return pickerArray[row]
}

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 Interacted

but 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 array

Working Output

enter image description here

0
On

This

if Array.count != 0 {

doesn't mean you can remove this index indexOfPicker , I think you need this

if indexOfPicker < Array.count {

As I guess you only select one time from the pickerView ( when the count is 5 which means indexOfPicker is in 0...4 ) then hit the minusButton 3 times