简体   繁体   中英

Not able to sort table view data in ascending order

I have an table view which will populate some data. Now I need to sort my 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()
    }
}

I tried with : let array = SearchedobjectArray.sorted(by: )

But I am not sure how can I sort this data with ascending order a to z . I tried with other sorted() also but not able to achieve.

When data is fetched in an array then you can simply sort the array on looName basis using the following code.

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

You need to sort your array of objects and then tableView.reloadData() . Here's a Playground example of how to sort your array:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM