本质上,我有一个 textField 按下时需要打开一个 UIPickerView 并带有来自 JSON 的选择
UIPickerView
在 Swift 中选择 a 并从 JSON 创建数组时,我分别致力于触发 a UItextField
,但在组合时遇到了一些麻烦。
对于JSON
我使用 Almofire 仅仅是因为它简化了流程并且UIPickerView
是通过编程方式编写的。
我正在使用的 JSON 如下所示:
[{“model”:”model1”},{“model":"model2”},
{“model":"model3”},{“model":"model4”},{“model":"model5”},{“model":"model6”}]
到目前为止,Almofire 看起来像这样:
let url = NSURL(string: "https://www.test.com/test/test")
let data = NSData(contentsOf: url! as URL)
var tmpValues = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
tmpValues = tmpValues as NSArray
reloadInputViews()
for candidate in tmpValues {
if let cdict = candidate as? NSDictionary {
//model is the column name in sql/json
let model = cdict["model"]
self.values.append(model! as AnyObject)
}
}
textField
使用以下代码触发打开 UIPickerView :
import UIKit
class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet weak var TextField: UITextField!
let model = ["model1","model2"]
var pickerview = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
TextField.inputView = pickerview
TextField.textAlignment = .center
TextField.placeholder = "Select Your Model"
pickerview.delegate = self
pickerview.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Names.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Names[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
TextField.text = Names[row]
}
}
如何用 JSON 响应替换硬编码数组?