无法将选定的值从UIPickerView保存到数组

问题描述

到目前为止,我已经尝试使用

func pickerView1(_ helpTypePicker: UIPickerView,didSelectRow row: Int,inComponent component: Int { 
  infoListinit.requestInfoList[4] = (helpTypePickerValues[row]) 
}

但是该值未保存到数组中。保存后我尝试打印该值,但无济于事。我的viewDidLoad函数中确实有helpTypePicker作为自委托,所以我不知道从这里去哪里。 UITextFields中的其他文本值可以很好地保存,但是我的UIPickerViews在这方面都没有作用

这是完整的课程:

import Foundation
import UIKit

class requestHelpTypePickerScreen: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView,numberOfRowsInComponent 
 component: Int) -> Int {
    if pickerView.tag == 1 {
        return helpTypePickerValues.count
    } else {
        return languagePickerValues.count
    }
}

func pickerView(_ pickerView: UIPickerView,titleForRow row: Int,forComponent component: Int) -> String? {
    if pickerView.tag == 1 {
        return "\(helpTypePickerValues[row])"
    } else {
        return "\(languagePickerValues[row])"
    }
}
// Mark: outlets
@IBOutlet weak var helpTypePicker: UIPickerView!
@IBOutlet weak var languagePicker: UIPickerView!
@IBOutlet weak var helpTypePickerLabel: UILabel!

let helpTypePickerValues = ["Academic/Professional","Donate","Food/Groceries","Medication","Emotional Support","Misc."]
let languagePickerValues = ["arabic","Chinese","Spanish","English","french","hindi/Urdu","Korean","Russian"]

override func viewDidLoad() {
    super.viewDidLoad()
    
    helpTypePicker.delegate = self
    languagePicker.delegate = self
    self.helpTypePicker.selectRow(2,inComponent: 0,animated: true)
    self.languagePicker.selectRow(3,animated: true)
}

// Mark: actions
@IBAction func buttonpressed(_ sender: Any) {
    func pickerView(_ helpTypePicker: UIPickerView,inComponent component: Int) {
        infoListinit.requestInfoList[5] = (helpTypePickerValues[row])
    }
    
    // this is called pickerView1 because it would conflict with the above 
    // function if called pickerView
    func pickerView1(_ languagePicker: UIPickerView,didSelectRow row1: Int,inComponent component: Int) {
        infoListinit.requestInfoList[6] = (languagePickerValues[row1])
    }
    performSegue(withIdentifier: "pickersDone",sender: nil)
}

解决方法

您的代码中有一个错误,委托表示当在UIPickerView中选择新行时,将调用函数pickerView(_:didSelectRow:inComponent:)(参数名称无关紧要)。 / p>

在您的情况下,当任何选择器选择新行pickerView(_:didSelectRow:inComponent:)时,将选择器作为参数传递到firs位置。您应该检查修改了哪个选择器,然后更改逻辑。

在您的情况下:

func pickerView(_ pickerView: UIPickerView,didSelectRow row: Int,inComponent component: Int) {
    if pickerView == helpTypePicker {
        infoListInit.requestInfoList[5] = helpTypePickerValues[row]
    } else {
        infoListInit.requestInfoList[6] = languagePickerValues[row]
    }
}