Ios 从pickerview中的选定行获取另一个值
我使用PickerView显示JSON数组中的数据 JSON数组有几个键,我正在合并其中两个键的值以填充pickerview:Ios 从pickerview中的选定行获取另一个值,ios,swift,Ios,Swift,我使用PickerView显示JSON数组中的数据 JSON数组有几个键,我正在合并其中两个键的值以填充pickerview: let fullName = (friendObj["nombre"] as! String) + " " + (friendObj["apellidos"] as! String) self.searchResults.append(fullName) 当用户选择一行时,所选值为字符串fullName: func pickerView(_ pickerVie
let fullName = (friendObj["nombre"] as! String) + " " + (friendObj["apellidos"] as! String)
self.searchResults.append(fullName)
当用户选择一行时,所选值为字符串fullName:
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return searchResults.count
}
//MARK: Delegates
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return searchResults[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print (searchResults[row])
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
如何将字符串fullName显示为行标题,而将另一个JSON键的值显示为结果
编辑:
do {
// Convert data returned from server to NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// Cleare old search data and reload table
self.searchResults.removeAll(keepingCapacity: false)
// If friends array is not empty, populate searchResults array
if let parseJSON = json {
if let friends = parseJSON["friends"] as? [AnyObject]
{
for friendObj in friends
{
let fullName = (friendObj["nombre"] as! String) + " " + (friendObj["apellidos"] as! String)
self.searchResults.append(fullName)
}
self.pickerAsesores.reloadAllComponents()
} else if(parseJSON["message"] != nil)
{
// if no friends returned, display message returned from server side
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
// display an alert message
self.displayAlertMessage(errorMessage!)
}
}
}
我的解决办法如下:
for friendObj in friends
{ let fullName = ["Nombre": friendObj["nombre"] as! String, "Apellidos": friendObj["apellidos"] as! String, "Id": friendObj["id"] as! String, "Tel": friendObj["tel"] as! String, "Email": friendObj["email"] as! String]
self.searchResults.append(fullName)
}
...
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print (searchResults[row]["Id"]!)
let prefs = UserDefaults.standard
prefs.setValue(searchResults[row]["Id"], forKey: "miAsesorId")
prefs.setValue(searchResults[row]["Nombre"]! + " " + searchResults[row]["Apellidos"]!, forKey: "miAsesor")
prefs.setValue(searchResults[row]["Tel"], forKey: "miAsesorTel")
prefs.setValue(searchResults[row]["Email"], forKey: "miAsesorEmail")
}
正如@Paulw11所说,我更改了字典的数组,现在可以正常工作了。与其存储每行中显示的字符串数组,不如存储一个表示JSON对象的对象数组,然后在
cellForRow:at
中获取相关字符串,以便填充行。@Paulw11,我一直在寻找如何将字符串数组转换为对象数组字符串已经是对象了,但我的意思是存储原始JSON信息。您还没有展示如何从JSON获取对象,但看起来您有一个字典;您应该在数组中存储任何friendObj
,而不是从中获取的字符串it@Paulw11,谢谢,我已经编辑了这个问题,包括如何获得JSON响应。我应该如何将JSON对象存储到searchResult?谢谢@Paulw11,我现在有了。我已经回答了我自己的问题