0

我正在尝试使用 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
    }    
}

谢谢你的帮助!

4

2 回答 2

0

if Array.count != 0 {

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

if indexOfPicker < Array.count {

我猜你只从 pickerView 中选择一次(当计数为 5 时,这意味着indexOfPicker在 0...4 中)然后点击减号按钮 3 次

于 2018-08-05T21:09:40.150 回答
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)只有当您在选择器中更改值时才会调用

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

工作输出

在此处输入图像描述

于 2018-08-06T05:53:33.963 回答