Teddy Chen
Teddy Chen

Reputation: 21

Alphabetic sequencing in TableView of iOS Swift 4

The original data is in JSON, which is downloaded and packed in to a Model Class called Article.swift. "article" is its element. We have

    article.name = rawData["A_Name_Ch"] as! String
    article.name_EN = rawData["A_Name_En"] as! String
    article.location = rawData["A_Location"] as! String
    article.image_URLString = rawData["A_Pic01_URL"] as? String
........
........

When showing the data on a tableviewController as below, data is sequenced by data's original sequence in JSON. It is sequenced by a key "ID". But, on Swift 4, how to sort it by AlphaBetic sequence referring to the key "article.name_EN"(in English)?

// MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(searchActive) {
            return filtered.count
        }
        return articles.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableCell", for: indexPath) as! ListTableCell

        var article : Article

        if(searchActive){   article = filtered[indexPath.row]   }
        else{   article = articles[indexPath.row]       }

        let imageURL: URL?
        if let imageURLString = article.image_URLString {
            imageURL = URL (string: imageURLString)
        }
        else {  imageURL = nil   }

        if let c = cell as? ListTableCell {

            c.nameLabel?.text = article.name;
            c.name_ENLabel?.text = article.name_EN;
            c.locationLabel?.text = article.location
            }   
        }
        return cell
    }

Upvotes: 0

Views: 87

Answers (1)

Maihan Nijat
Maihan Nijat

Reputation: 9334

You need to sort your object of the array by property name.

articles.sorted(by: { $0.name_EN > $1.name_EN })

For Asc:

articles.sorted(by: { $0.name_EN < $1.name_EN })

You have both filtered array and original array. Apply the sort on both arrays before populating to the tableView.

Upvotes: 1

Related Questions