如何使用UIButton在pickerView中删除所选位置?

时间:2018-08-05 20:55:22

标签: swift swift4 pickerview

我正在尝试使用UIButton删除pickerView的元素,但是在连续删除3个元素后,我得到了错误(索引超出范围)。

对不起,我英语不好,我还很年轻,住在德国: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
    }    
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

if Array.count != 0 {

并不意味着您可以删除该索引indexOfPicker,我认为您需要这个

if indexOfPicker < Array.count {

我猜您只能从pickerView中选择一次(当计数为5时表示indexOfPicker在0 ... 4),然后按下minusButton 3次

答案 1 :(得分:0)

只需替换您的功能

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

使用

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

问题

从数组索引中删除一个元素时,该元素没有得到更新,因为func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)仅在您更改选择器中的值时 Interacted

时才被调用

但是在重新加载时,您需要更新索引,因此,每次重新加载选择器时都会调用func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int),这会在您重新加载或更新数组时更新所选索引

工作输出

enter image description here