【问题标题】:Auto Sort UICollectionViewCell based on parameter in JSON swift根据 JSON swift 中的参数自动排序 UICollectionViewCell
【发布时间】:2017-01-24 12:24:21
【问题描述】:

我有一个 UICollectionView,其中包含从 JSON 响应数据填充的单元格。目前,单元格按类别填充,一切顺利。

我的问题是单元格按字母顺序排序,这就是它们在 JSON 文件中的排序方式,但我希望它们按每个类别包含的“喜欢计数”参数排序。

到目前为止,我已经找到了如何使用户能够拖动和重新排列单元格,但我想根据每个类别的“喜欢”数量按降序实现“自动排序”。

感谢您的帮助。

编辑 - 使用 Alamofire 进行 API 调用和 Swiftyjson 进行解析。

Alamofire.request(.GET, "mydomain").responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {

                let swiftyJsonVar = JSON(responseData.result.value!)

                if let resData = swiftyJsonVar.arrayObject {

                    self.arrRes = resData as! [[String:AnyObject]]


                }

                if self.arrRes.count > 0 {

                   self.collectionView.reloadData()


                }
            }
        }

为单元格设置标签

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HomeCollectionViewCell
        var dict = arrRes[indexPath.row]

        cell.catLabel.text = dict["name"] as? String
        let likes = dict["likes count"] as? Int
        cell.layoutIfNeeded()

        return cell
    }

【问题讨论】:

  • 向我们展示您用于进行 api 调用的响应/模型类和代码。
  • 对数据源进行排序并重新加载数据(如果需要)。
  • 我已更新我的问题以包含我正在使用的代码。我可以使用 Swiftyjson 返回计数数组,我只是不确定如何使用该信息进行排序。我还是个新手,如果这个要求太简单了,我深表歉意。

标签: ios json sorting uicollectionviewcell


【解决方案1】:

假设数据是一个字典数组,“喜欢”计数是字典中的一个键值对,您可以使用它们对它们进行排序

array.sortInPlace({$0.likes > $1.likes})

【讨论】:

    【解决方案2】:

    yourArray = JSON 响应数据获取数组;

    NSArray *sortedArray = [yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"likes" ascending:NO]]];
    

    & 然后应用于排序数组中的UICollectionView 数据源 & 重新加载你的UICollectionView

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多