无法按升序对表视图数据进行排序

时间:2019-04-12 04:54:13

标签: ios swift uitableview

我有一个表格视图,它将填充一些数据。现在,我需要按升序对表格视图数据进行排序。

var SearchedobjectArray = [Objects]()

struct Objects {
    var looId : String!
    var looName : String
    var looImageUrl:String!
    var looCategoryType:String!
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier:"cell", for: indexPath) as? MyLooCell{
        cell.looImage.setShowActivityIndicator(true)
        cell.looImage.setIndicatorStyle(.gray)
        let imageURL = SearchedobjectArray[indexPath.row].looImageUrl

        if (imageURL?.isEmpty)! {
            let imageUrl = self.getDefaultImageForCategory(categoryName: SearchedobjectArray[indexPath.row].looCategoryType)
            cell.looImage.image = UIImage(named: imageUrl)
        } else {
            cell.looImage.sd_setImage(with: URL(string: SearchedobjectArray[indexPath.row].looImageUrl))
        }
        cell.looName.text = SearchedobjectArray[indexPath.row].looName
        let looCatType = SearchedobjectArray[indexPath.row].looCategoryType
    } else {
        return UITableViewCell()
    }
}

我尝试过:let array = SearchedobjectArray.sorted(by: )

但是我不确定如何以升序a to z对数据进行排序。我也尝试了其他sorted(),但无法实现。

2 个答案:

答案 0 :(得分:1)

在数组中提取数据时,您可以使用以下代码简单地基于looName对数组进行排序。

SearchedobjectArray = SearchedobjectArray.sorted(by: { $0.looName > $1.looName})
tableView.reloadData()

答案 1 :(得分:0)

您需要对对象数组进行排序,然后对tableView.reloadData()进行排序。这是一个如何对数组进行排序的Playground示例:

import Cocoa

struct Objects {
    var looId : String!
    var looName : String
    var looImageUrl:String!
    var looCategoryType:String!
}

var SearchedobjectArray = [Objects]()

let c = Objects(looId: "Chase", looName: "Chase", looImageUrl: "Chase", looCategoryType: "Chase")
SearchedobjectArray.append(c)

let b = Objects(looId: "Bree", looName: "Bree", looImageUrl: "Bree", looCategoryType: "Bree")
SearchedobjectArray.append(b)

let a = Objects(looId: "Adam", looName: "Adam", looImageUrl: "Adam", looCategoryType: "Adam")
SearchedobjectArray.append(a)

print("Before sorting")
print(SearchedobjectArray)

// The real sorting is happening here...I guessed you wanted to sort by looName
SearchedobjectArray = SearchedobjectArray.sorted(by: { $0.looName < $1.looName })
print("After sorting")
print(SearchedobjectArray)