簡體   English   中英

無法按升序對表視圖數據進行排序

[英]Not able to sort table view data in ascending order

我有一個表格視圖,它將填充一些數據。 現在,我需要按升序對表格視圖數據進行排序。

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()但無法實現。

當在數組中獲取數據時,您可以使用以下代碼簡單地基於looName對數組進行排序。

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

您需要對對象數組進行排序,然后對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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM