根据单元格从数组中获取数据以获取索引

时间:2019-02-12 13:05:22

标签: ios swift4

我有很多类似的字典

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]]

数据来自服务器

我想基于项目索引的单元格在collectionview中显示此数据。谁能帮助我做到这一点?

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 个答案:

答案 0 :(得分:1)

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。

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解析为字典。

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中的人员数组填充集合视图。

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

注意:此代码尚未经过测试,JSON解析器和转换对于从服务器接收到的JSON可能有所不同。