在Swift中按字母顺序在TableView上排序数组

问题描述 投票:0回答:1

我已经很好地,确实地搜索了Stack Overflow,提供了各种不同的选项,但似乎都无法正常工作。

我有一个应用程序,该应用程序包含NFL(例如,犯罪/防御)等的术语表。它来自JSON API,并且存储在本地。我想以编程方式对数据进行排序,因此这些术语均按字母顺序在其各自的部分(“ A”,“ B”,“ C”等)中列出。

View Controller:

import UIKit

class GlossaryVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    private let glossaryCellId = "GlossaryCell"

    var glossarys = [Offence]()
    var filteredGlossarys = [Offence]()
    private var subCategorySet: Set<String> = []
    private var glossarysDictionary: [String: [Offence]] = [:]

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var noResultsView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        filteredGlossarys = glossarys

        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clear

        searchBar.delegate = self

        noResultsView.isHidden = true

        hideKeyboardWhenTappedAround()

    }

    override func viewDidAppear(_ animated: Bool) {

        DataProvider.getData(with: .GLOSSARY_DATA_URL) { (letters) in

            self.glossarys = letters.flatMap { $0.offences }
            self.filteredGlossarys = self.glossarys
            self.groupGlossarys()

        }

    }

    func groupGlossarys() {
        glossarysDictionary.removeAll()
        subCategorySet.removeAll()
        for glossary in filteredGlossarys {
            subCategorySet.insert(glossary.glossaryLetter!)
        }

        for subCategory in subCategorySet {
            glossarysDictionary[subCategory] = []
        }

        for glossary in filteredGlossarys {
            var list = glossarysDictionary[glossary.glossaryLetter!]
            list?.append(glossary)

            glossarysDictionary[glossary.glossaryLetter!] = list
        }
        checkAndShowTableView()
    }

    func checkAndShowTableView() {
        if subCategorySet.count > 0 {
            tableView.isHidden = false
            noResultsView.isHidden = true
            tableView.reloadData()
        } else {
            tableView.isHidden = true
            noResultsView.isHidden = false
        }
    }

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.font = UIFont(name: "Nano", size: 17)!
        header.textLabel?.textColor = UIColor.white
        header.textLabel?.textAlignment = .center
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return subCategorySet.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let subCategoryList = Array(subCategorySet)
        return subCategoryList[section]
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let subCategoryList = Array(subCategorySet)
        let glossaryList = glossarysDictionary[subCategoryList[section]]
        return glossaryList!.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let glossaryCell = tableView.dequeueReusableCell(withIdentifier: glossaryCellId, for: indexPath) as? GlossaryCell else {
            fatalError("Unable to dequeue contact cell")
        }

        let subCategoryList = Array(subCategorySet)
        let glossaryList = glossarysDictionary[subCategoryList[indexPath.section]]
        glossaryCell.configure(glossary:(glossaryList?[indexPath.row])!)
        return glossaryCell

    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor.clear
        cell.contentView.backgroundColor = UIColor.clear
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let viewGlossaryDetailsVC = segue.destination as? GlossaryDetailsVC,
            let section = tableView.indexPathForSelectedRow?.section, let row = tableView.indexPathForSelectedRow?.row {
            let subCategoryList = Array(subCategorySet)
            let glossaryList = glossarysDictionary[subCategoryList[section]]
            let glossarys = glossaryList?[row]
            viewGlossaryDetailsVC.glossarys = glossarys
        }
    }

}


extension GlossaryVC: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if !searchText.isEmpty {
            filteredGlossarys = glossarys.filter({ (glossary) -> Bool in
                let glossaryTitleRange = glossary.glossaryTitle?.range(of: searchText, options: .caseInsensitive)
                let glossaryDescriptionRange = glossary.glossaryDescription?.range(of: searchText, options: .caseInsensitive)
                let glossaryKeywordsRange = glossary.glossaryKeywords?.range(of: searchText, options: .caseInsensitive)
                return glossaryTitleRange != nil || glossaryDescriptionRange != nil || glossaryKeywordsRange != nil
            })
        } else {
            filteredGlossarys = glossarys
        }
        groupGlossarys()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
}

到目前为止,我已经在sorted(by: {})中的let subCategoryList = Array(subCategorySet)上尝试了titleForHeaderInSection方法,该方法的确按字母顺序排列了节标题,但数据没有改变。因此,您最终在“ A”子类别中有以“ H”开头的单词。

根据数据库中的“字母”键对数据进行分组,例如,因此将所有“ A”分组在一起,等等。

任何帮助将不胜感激,我所要做的就是按字母顺序对它进行排序,我觉得自己的深度有点不足。我仍然使用Swift 3,因为这对我来说是个人的爱好。

arrays swift sorting uitableview
1个回答
0
投票

您可以尝试这个:

self.glossarys.sorted { $0.offences < $0.offences }

希望有帮助...

© www.soinside.com 2019 - 2024. All rights reserved.