gpt4 book ai didi

swift - 如何使用 UIButton 删除 pickerView 中选定的位置?

转载 作者:行者123 更新时间:2023-11-30 11:16:29 26 4
gpt4 key购买 nike

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

感谢您的帮助!

最佳答案

只需替换你的函数

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) ,从而更新您选择的索引当您重新加载或更新数组时

工作输出

enter image description here

关于swift - 如何使用 UIButton 删除 pickerView 中选定的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com