我有一个问题在Swift中使用Json源代码。Swift 3过滤器Json&重新排序
在一个泰伯维我得到JSON的来源:
let url = URL(string: "http://url")!
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: url) { (data, response, error) in
let jsonData = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
//adressiere Array in JSON Dictionary
self.Devs = jsonData?["devices"] as! [[String:AnyObject]]
我的didSelectRowAt部我让用户选择的行和将JSON的ID被添加到UserDefault阵列。
在第一的ViewController我具有相同的Json代码如上述,但我与UserDefault阵列过滤它:
devArray是包含用户选择的ID的数组。
let jsonData = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
//adressiere Array in JSON Dictionary
self.Devs = jsonData?["devices"] as! [[String:AnyObject]]
//Filter Array
let filterarray = self.devArray
self.filteredArray = self.Devs.filter { filterarray.contains($0["id"] as! String) }
这第一视图控制器具有的CollectionView,我已经实现了重新排序的单元格中的功能:
func collectionView(_ collectionView: UICollectionView,
moveItemAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath)
{
// TODO: Update data model to reflect the change
let temp = devArray[sourceIndexPath.row]
devArray[sourceIndexPath.row] = devArray[destinationIndexPath.row]
devArray[destinationIndexPath.row] = temp
}
这重新排列devArray,和它的作品(我把它打印到控制台) 但只要刷新视图,它就会返回并按照Ids来自json源的顺序进行排序。 我必须拉Json,因为我需要从json源代码更改的值。
有没有人有想法?我希望我描述了我的问题吧;-)
我cellForItemAt:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let colcel = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
let devListItem = filteredArray[indexPath.row]
//Attribute
let devListValue = (devListItem["attributes"]?.value(forKey: "value"))
let resultDevListValue = String(describing: devListValue!)
//Cell Text & Color & See if it is a Switch
if (devListItem["template"]?.contains("switch"))! {
if resultDevListValue.contains("0") {
colcel.topLabel.text = devListItem["name"] as? String
} else {
colcel.topLabel.text = devListItem["name"] as? String
}
} else {
//print("kein switch")
}
return colcel
}
您是否也可以发布cellForItemAtIndexPath方法?您可能正在错误地访问您的数据源 – Lope
我在上面插入了方法 – theslash
请检查我的答案,这可能是您的问题的原因。作为一个附注,我强烈建议为“dev”创建模型对象,并使用它来代替从JSON解析器获得的字典数组。将来维护和使用将更加容易 – Lope