gpt4 book ai didi

ios - Swift 3 过滤 Json 和重新排序

转载 作者:行者123 更新时间:2023-11-30 12:33:01 25 4
gpt4 key购买 nike

我在使用 Json 源的 Swift 中遇到了一些问题。

在一个 Tableview 中我得到了 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) }

第一个 Viewcontroller 有一个 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 进行了重新排序,并且它有效。(我将其打印到控制台)但是,一旦我刷新 View ,它就会返回并按照 Id 来自 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
}

最佳答案

您正在 cellForItemAt 方法中基于filteredArray 构建单元格:

let devListItem = filteredArray[indexPath.row]

但是当你移动单元格时,你会更新 devArray

let temp = devArray[sourceIndexPath.row]
devArray[sourceIndexPath.row] = devArray[destinationIndexPath.row]
devArray[destinationIndexPath.row] = temp

我假设这是两个不同的数组。您需要在两个地方使用相同的数组,或者在移动单元格时同步它们

关于ios - Swift 3 过滤 Json 和重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com