根据索引处项目的单元格从数组中获取数据 [英] getting data from an array based on cell for item at index

查看:24
本文介绍了根据索引处项目的单元格从数组中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆字典,比如

var array = [["name":abc,"number":123,"address":xyz],["name":def,"number":456,"address":yzx],["name":ghi,"number":789,"address":ooo],["name":jkl,"number":012,"address":ppp]]

来自服务器的数据

我想根据项目索引的单元格在集合视图中显示此数据.谁能帮我做这件事?

I want to display this data in a collectionview, based on cell for item index. Can anyone help me to do this?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HistoryCollectionViewCell
    var dict = pro[indexpath]
    cell.nameobj.text = dict["name"] as! String
    cell.addressobj.text = dict["address"] as! String
    return cell    
}

推荐答案

1) 创建个人类

class Person : NSObject {

    var name = ""
    var number = ""
    var address = ""

    static let sharedInstance: PersonModel = PersonModel()


    func getPersonModel(_ dictionary:NSDictionary) -> Person{
        let person = Person()
        person.name = dictionary.object(forKey: "name") as! String
        person.number = dictionary.object(forKey: "number") as! String
        person.address =  dictionary.object(forKey: "address") as! String
        return person
    }
}

2) 将您的 json 映射到相应 viewController 中的 person 对象模型,下一点返回可在此处使用的解析后的 json.

2) Map your json to person object model in the respective viewController the next point return the parsed json which can be used in here .

let personDict = convertStringToDictionary(text: "Json obtained from server")
let personArray = personDict.object(forKey: "Person") as! NSArray
for person in PesronArray {
    let personModel = PersonModel.sharedInstance.getPersonModel(personDict as! NSDictionary)
    persons.add(personModel)
}

3) 您可以使用此方法或创建您自己的扩展来将 json 解析为字典.

3) You can use this method or create your own extension to parse the json into dictionary.

func convertStringToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil

    }

4) 您可以使用步骤 2 中的人数组填充集合视图.

4) You can populate the collection view Using the persons array form the step 2.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
        let personObject = persons.object(at: indexPath.row) as? Person
}

注意:此代码未经测试,json 解析器和转换可能会因从服务器接收到的 JSON 而有所不同.

这篇关于根据索引处项目的单元格从数组中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆