按每个对象的布尔值排序并显示在集合视图中

时间:2019-03-07 11:35:55

标签: ios swift sorting

我有一个UITableView,我正在使用UICollectionView。因此,我有多个集合视图-用户可以在其中水平滚动。现在,在每个集合视图中,我都需要显示一些数据。但是每个单元格对象都包含bool值。如果bool为假,那么我需要在集合视图中首先显示该对象标题,然后再显示bool为真。

我的JSON如下:

first obj:({
     name =ruler1;
     com = "        1";
     Dele = "";
     isTrue = false
 },
 {
     name =rule2r;
     com = "        1";
     Dele = "";
     isTrue = true
 },
 {
     name =rule3r;
     com = "        1";
     Dele = "";
     isTrue = false
 })

 sec obj:({
     name =ruler name1;
     com = "        1";
     Dele = "";
     isTrue = true
 },
 {
     name =ruler name 2;
     com = "        1";
     Dele = "";
     isTrue = false
 },
 {
     name =ruler name 3;
     com = "        1";
     Dele = "";
     isTrue = false
 })

cellForRowAtIndexPath中,我只是像正常显示标签一样:

collectionCell.cellTitleLabel.text = Info["name"] as? String ?? ""

但是,如何分类显示哪个对象为假?首先需要证明这一点。

例如:

ruler1 (false), rule3r(false) , rule2r(true)一样。

有什么有用的解决方案吗?我已经尝试过排序,但是并没有太大帮助。

更新:

我有以下代码以collectionView方法在cellForRowAtIndexPath中显示标签:

if let gamesList = skillInfo?["data_list"]  as? [[String: Any]] {
    let gameInfo = gamesList[indexPath.item]
    collectionCell.cellTitleLabel.text = gameInfo["name"] as? String ?? ""
}

skillInfo是我添加到捆绑软件中的JSON列表。

3 个答案:

答案 0 :(得分:0)

您可以按查看步骤排序:

  1. 将JSON数组设置为对象模型

  2. 然后使用此函数对数组进行排序

例如您的数据数组为:arrData

然后使用:

arrData.sort { (first, second) -> Bool in

return !first. isTrue

 }

首先将假值对象排序

答案 1 :(得分:0)

使用以下代码通过布尔值获取支持的字典数组。

let sortedArray = (myArray as NSArray).sortedArray(using: [NSSortDescriptor(key: "isTrue", ascending: false)]) as! [[String:AnyObject]]

如果您想首先获得真值,那么ascending = false,如果您想首先获得假值,则通过ascending = true

在此屏幕快照中,看到输出对字典数组进行了排序。

enter image description here

答案 2 :(得分:0)

这对字典数组进行排序。

在这里,升序= true将首先返回isTrue = 0的数据,

当ascending = false时,将首先返回isTrue = 1的数据。

您可以通过以下一行来满足您的需求,尝试以下代码,让我知道您是否还有任何问题。

 func sortJSONArray() {

    let bundle = Bundle.init(for: StackOverflowViewController.self)

    guard let jsonPath = bundle.path(forResource: "StackOVerflow", ofType: "json"),
        let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else {
            return
    }

    if let jsonObjects = (try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization
        .ReadingOptions.allowFragments)) as? NSArray {

        let arrFiltered = jsonObjects.filter{($0 as! [String: Any])["isTrue"] as? Int == 0}
        let arrSorted = jsonObjects.sortedArray(using: [NSSortDescriptor(key: "isTrue", ascending: true)]) as! [[String:AnyObject]]

        print(arrFiltered)
        print(arrSorted)
    }
}

这用于过滤字典数组,(如果您只想显示isTrue = 0的数据)

let arrFiltered = jsonObjects.filter{($0 as! [String: Any])["status"] as? Int == 0}