У меня есть JSON-сценарий со следующей структурой:
[{"manufacturer”:”exampleManufacturer”,”model":"exampleModel”}]
В настоящее время у меня есть следующая настройка UIPickerView, которая отображает первый столбец manufacturer
. Как я могу отобразить второй столбец model
в том же UIPickerView?
Второй столбец зависит от того, что выбрано для первого столбца, поэтому он должен перезагрузиться.
Ниже показано, как я покажу первый столбец manufacturer
:
import UIKit
class CreateRMA_ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var customerTextField: UITextField!
var pickerView: UIPickerView!
var values: [AnyObject] = []
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.values.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let titleRow = (values[row] as? String)!
return titleRow
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if values.count > 0 && values.count >= row{
self.customerTextField.text = self.values[row] as? String
self.pickerView.isHidden = true
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
//when you select the text field the picker view will be visible
if(textField == self.customerTextField){
self.pickerView.isHidden = false
self.view.endEditing(true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLoad() {
super.viewDidLoad()
pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
//get the values from sql/Json
let url = NSURL(string: "https://www.example.com/test/test.php")
let data = NSData(contentsOf: url! as URL)
var tmpValues = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
tmpValues = tmpValues.reversed() as NSArray
reloadInputViews()
for candidate in tmpValues {
if let cdict = candidate as? NSDictionary {
//fullName is the column name in sql/json
let names = cdict["customer"]
self.values.append(names! as AnyObject)
}
}
}
}
Пример JSON:
[{"manufacturer":"GE","model":"1147"},{"manufacturer":"GE","model":"34983"},{"manufacturer":"Apple","model":"8Plus"},{"manufacturer":"Samsung","model":"Galaxy 8"},{"manufacturer":"Samsung","model":"Note 5"},{"manufacturer":"Samsung","model":"Note 8"}]