0

我目前正在使用 Swift 开发一个应用程序,其中我使用 UIPickerView。我想在pickerView(myPickerView)中设置值

let PickerData = {
"listOfGrouoc": {
    "1": "DDDDD",
    "2": "SDDDDD",
    "3": "TTTT"
},
"TypeOfGrpos": [
    "STTTTT",
    "TTTTT"
],
"SubTypp": {
    "3": "Shh",
    "6": "SSS",
    "9": " dfdf"
    "14": "Shh",
    "21": "SSS",
    "60": " dfdf"
},
"GropName": {
    "1": "test",
     "2": "test"
    }
  }

这是来自服务器的响应我想在pickerView中显示组listOfGrouoc

下面的代码: -

viewDidLoad我有:

Picker.delegate = self
Picker.dataSource = self

然后我有所需的方法:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
            return 1
        }

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return PickerData.count
        }

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return PickerData[row] trying to show SSSSS,DDDDD,GGGGG
        }

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
       print(PickerData[row]) expecting only id Int Value
    }

问题:- 有人可以向我解释如何在选择器视图标题中设置 dict 值以及单击 didSelectRow 时获取 dict key 。任何帮助将不胜感激。

提前致谢。

4

1 回答 1

2

从您的数据中,我创建新的对象名称CustomObject并解析将在选择器中显示的数据。

这是我的代码:

struct CustomObject {
    let id: String
    let name: String
    init(id: String, name: String) {
        self.id = id
        self.name = name
    }
}
class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    let PickerData: [String : Any] = ["listOfGrouoc": ["1": "DDDDD","2": "SDDDDD","3": "TTTT"],"TypeOfGrpos": ["STTTTT","TTTTT"],"SubTypp": ["333": "Shh","334": "SSS","543": " dfdf"],"GropName": ["1": "test","2": "test"]]
    var listOfGrouoc: [CustomObject] = []


    override func viewDidLoad() {
        super.viewDidLoad()

        let picker = UIPickerView(frame: CGRect(x: 0, y: 50, width: 300, height: 200))
        picker.dataSource = self
        picker.delegate = self
        self.view.addSubview(picker)

        if let list = PickerData["listOfGrouoc"] as? [String: String] {
            for objectID in list.keys {
                if let name = list[objectID] {
                    self.listOfGrouoc.append(CustomObject(id: objectID, name: name))
                }
            }
        }
        //Sort here
        self.listOfGrouoc.sort(by: { $0.id < $1.id})
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return listOfGrouoc.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return listOfGrouoc[row].name
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print(listOfGrouoc[row].id)
    }
}
于 2020-05-05T09:54:06.507 回答