我以编程方式编写了以下UIPickerView,以提取从JSON获取的值。
基本上,在选择customerTextField
时,应该会看到UIPickerView出现,其中包含来自正在解析的链接的值。
相反,我只是看到一个键盘出现。
是否存在语法问题,我没有收到任何错误,UIPickerView根本没有显示。
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)
}
}
}
}
答案 0 :(得分:0)
在ViewDidLoad()
中,您创建了pickerView
,将delegate
和dataSource
设置为self,很好。但是您尚未完成的工作,还没有将pickerView
添加为UITextfield
的{{1}}。这就是为什么您没有获取pickerView
这样做
inputView
您还需要做其他事情,在override func viewDidLoad() {
// do your works
pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
customerTextField.inputView = pickerView
}
中删除与UIPickerView
相关的代码块。
答案 1 :(得分:0)
您必须将文本字段的inputView
设置为pickerView
override func viewDidLoad() {
super.viewDidLoad()
pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
customerTextField.inputView = pickerView
}