0
我正在使用PickerView來顯示來自JSON數組的數據。在pickerview中從選定行中獲取另一個值
的JSON陣列具有多個鍵,我從兩個鍵的合併值來填充pickerview:
let fullName = (friendObj["nombre"] as! String) + " " + (friendObj["apellidos"] as! String)
self.searchResults.append(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!)
}
}
}
而不是存儲在每行中顯示的字符串數組,您應該存儲表示您的JSON對象的對象數組,然後在'cellForRow:at'中獲取相關字符串以填充行。 – Paulw11
@ Paulw11,我一直在尋找如何將字符串數組轉換爲對象數組 – mvasco
字符串已經是對象,但我的意思是存儲原始的JSON信息。你沒有展示你如何從JSON獲取對象,但它看起來像你有一本字典;你應該在數組中存儲任何'friendObj',而不是你從它得到的字符串 – Paulw11