我正在尝试使用来自API的响应来填充UIPickerView
,我可以使用基本的JSON响应成功完成此操作,但是我确实为下面的示例(其中JSON以数组形式返回值)感到困惑。
下面的代码来自一个Playground,已经简化为仅显示相关代码,我相信,如果我可以使用正确格式的数组创建变量,那么可以使用它来填充{{1} },但我已经包含了UIPickerView
代码,以防万一我以错误的方式进行操作。
我已经搜索并尝试改编了该论坛和其他论坛中的各种示例,但是由于某种原因,我只是无法使其正常工作,我是Swift的新手,所以我处于学习曲线上!>
我最近的是UIPickerView
,但我需要得到account(data: ["account1", "account2", "account3"])
我希望有人能提供帮助,但希望不要对这个问题投反对票。
["account1", "account2", "account3"]
答案 0 :(得分:0)
我终于使用下面的代码作为解决方案的基础对它进行了排序
import UIKit
struct Account: Codable {
var data: [String]
}
class ViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet private var displayLabel: UILabel!
@IBOutlet private var pickerView: UIPickerView!
// MARK: - Internal Variables'
var account: Account?
// MARK: - IBActions
@IBAction private func showPicker(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
pickerView.isHidden = !sender.isSelected
}
private func createAccountList() {
let json = """
{
"returnResult":1,
"data":["account1", "account2", "account3","account4", "account5", "account6"]
}
"""
do {
account = try JSONDecoder().decode(Account.self, from: json.data(using: .utf8)!)
} catch {
print(error.localizedDescription)
}
}
private func initUI() {
pickerView.delegate = self
pickerView.dataSource = self
}
override func viewDidLoad() {
super.viewDidLoad()
createAccountList()
initUI()
pickerView.reloadAllComponents()
// Do any additional setup after loading the view, typically from a nib.
}
}
extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return account?.data.count ?? 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return account?.data[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
displayLabel.text = account?.data[row]
}
}
可以在Github https://github.com/techmehra/uipicker-demo
上找到该项目。我确实需要稍微修改代码以使其与实时API响应一起工作。