首页 > 解决方案 > 如何获取存储在变量中的数组值并在表格视图中显示它们?

问题描述

我在使用 Alamofire 的 Post 请求的 JSON 响应中有这个数组

"emergency_contacts": [
            {
                "id": 8,
                "user_id": 11,
                "first_name": "abc",
                "last_name": "abc",
                "email": "svsg@hh.ggg",
                "phone_number": "+27676800080",
                "created_at": "2020-07-30T23:09:10.000000Z",
                "updated_at": "2020-07-30T23:09:10.000000Z",
                "deleted_at": null
            }
            {
                "id": 9,
                "user_id": 11,
                "first_name": "xxc",
                "last_name": "xxc",
                "email": "sh2.ggg",
                "phone_number": "+27676800080",
                "created_at": "2020-07-30T23:09:10.000000Z",
                "updated_at": "2020-07-30T23:09:10.000000Z",
                "deleted_at": null
            }
        ],

我已经保存了这样的回复

let arrayData = userData["emergency_contacts"] as! NSArray

我如何在某些 var 中有这些值并在 tableView 中显示这些数组?

标签: swiftxcodealamofire

解决方案


请尝试此代码

extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
    
    let dicData = arrayData.object(at: indexPath.row) as? NSDictionary
    print(dicData?.value(forKey: "id") as Any)
    print(dicData?.value(forKey: "user_id") as Any)
    print(dicData?.value(forKey: "first_name") as Any)
    print(dicData?.value(forKey: "last_name") as Any)
    print(dicData?.value(forKey: "email") as Any)
    print(dicData?.value(forKey: "phone_number") as Any)
    print(dicData?.value(forKey: "created_at") as Any)
    print(dicData?.value(forKey: "updated_at") as Any)
    print(dicData?.value(forKey: "deleted_at") as Any)
    
    return cell
  }
}

推荐阅读