如何使用自定义模型类按节按字母顺序对tableView中的数据进行排序? [英] How do you sort data in a tableView alphabetically by section using a custom model class?

查看:57
本文介绍了如何使用自定义模型类按节按字母顺序对tableView中的数据进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编码的新手,一直在尝试按表的字母顺序对表视图行中的数据(名称)进行排序.我已经设法创建了部分和一个索引,但是无法弄清楚如何对名称进行排序.每个部分都有相同的A-Z名称列表.

I'm new to coding and have been trying to sort the data (names) in my tableview rows alphabetically by section. I've managed to create the sections and an index, but can't figure out how to get the names to sort; every section has the same list of names from A-Z.

我有一个名称类的模型类,该类具有对象:nameTitle,nameDetail,图像,纬度坐标和经度坐标. tableView显示nameTitle.text.其余对象在另一个视图控制器中显示或访问.

I have a model class of Names that has objects: nameTitle, nameDetail, image, latitude coordinates and longitude coordinates. The tableView displays nameTitle.text. The rest of the objects are displayed or accessed in another view controller.

这是我的TableViewController中的示例代码:

Here is sample code from my TableViewController:

import UIKit

class TableOfContentsVC: UIViewController, UITableViewDelegate,  UITableViewDataSource {

@IBAction func backButtonPressed(_ sender: Any) {

    dismiss(animated: false, completion: nil)

}

@IBOutlet weak var tableView: UITableView?

var name = [Name]()

override func viewDidLoad() {
    super.viewDidLoad()

    let cell001 = Name (nameTitle: "Acker" , nameDetail: "Details for Acker are listed here.", picture: UIImage (named: "somePicture.jpg"), latCoordinates: 38, longCoordinates: 119)

    name.append (cell001)

    let cell002 = Name (nameTitle: "Baker" , nameDetail: "Details for Baker are listed here.", picture: UIImage (named: "somePicture.jpg"), latCoordinates: 38, longCoordinates: 119)

    name.append (cell002)

    let cell003 = Name (nameTitle: "Caker" , nameDetail: "Details for Caker are listed here.", picture: UIImage (named: "somePicture.jpg"), latCoordinates: 38, longCoordinates: 119)

    name.append (cell003)

    let cell004 = Name (nameTitle: "Dacker" , nameDetail: "Details for Dacker are listed here.", picture: UIImage (named: "somePicture.jpg"), latCoordinates: 38, longCoordinates: 119)

    name.append (cell004)

    let cell005 = Name (nameTitle: "Ecker" , nameDetail: "Details for Ecker are listed here.", picture: UIImage (named: "somePicture.jpg"), latCoordinates: 38, longCoordinates: 119)

    name.append (cell005)

    let cell006 = Name (nameTitle: "Facker" , nameDetail: "Details for Facker are listed here.", picture: UIImage (named: "somePicture.jpg"), latCoordinates: 38, longCoordinates: 119)

    name.append (cell006)
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
    let currentCollation = UILocalizedIndexedCollation.current() as UILocalizedIndexedCollation
    return currentCollation.section(forSectionIndexTitle: index)
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let currentCollation = UILocalizedIndexedCollation.current() as UILocalizedIndexedCollation
    let sectionTitles = currentCollation.sectionTitles as NSArray
    return sectionTitles.object(at: section) as? String

}

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    let currentCollation = UILocalizedIndexedCollation.current() as UILocalizedIndexedCollation
    return (currentCollation.sectionIndexTitles as NSArray) as? [String]


}

func numberOfSections(in tableView: UITableView) -> Int {
    let currentCollation = UILocalizedIndexedCollation.current() as UILocalizedIndexedCollation
    let sectionTitles = currentCollation.sectionTitles as NSArray
    return sectionTitles.count

}


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

    if let cell = tableView.dequeueReusableCell(withIdentifier: "NameCell", for: indexPath) as? NameCell {

        let name = Name [indexPath.row]

        cell.updateUI(name: name)

    return cell


    } else {

        return UITableViewCell()

    }
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return name.count


}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let name = names [indexPath.row]
    performSegue(withIdentifier: "ContentVC", sender: name)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? ContentVC {

        if let name = sender as? Name {
            destination.name = name
        }
    }
}  
}

除了使名称按字母顺序显示在相应部分中之外,所有其他操作都很好.我已经尝试了10种不同的方法来使它正常工作,但没有任何帮助.任何建议将不胜感激.预先感谢!

Everything works great except for getting the names to show up in the respective section alphabetically. I've tried about 10 different ways to get this to work and nothing has helped. Any suggestions would be greatly appreciated. Thanks in advance!

推荐答案

您做错了方法.您没有使用数据来生成索引.

You are doing it the wrong way. You are not using your data to generate your index.

让我们考虑一下您的数据数组var name: [Name]

Let's consider you have an array of your data var name: [Name]

  1. 定义每个Name所属的部分:
  1. Define the section into which every Name belongs:

extension Name {
    var titleFirstLetter: String {
        return String(self.nameTitle[self.nameTitle.startIndex]).uppercased()
    }
}

  1. 根据您的数据生成索引

// all the first letters in your data
let firstLetters = names.map { $0.titleFirstLetter }
// some letters appear multiple times, let's remove duplicates
let uniqueFirstLetters = Array(Set(firstLetters))
// sort them
// this is your index
let sortedFirstLetters = uniqueFirstLetters.sorted()

  1. 生成版块

let sections: [[Name]] = sortedFirstLetters.map { firstLetter in
    return names
        .filter { $0.titleFirstLetter == firstLetter } // only names with the same first letter in title
        .sorted { $0.nameTitle < $1.nameTitle } // sort them
}

  1. 使用它们

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sortedFirstLetters[section]
}

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return sortedFirstLetters
}

func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count // or sortedFirstLetters.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let name = sections[indexPath.section][indexPath.row]
    ...
}

编辑-完整示例:

class Name {
    let nameTitle: String
    let nameDetail: String

    init(nameTitle: String, nameDetail: String) {
        self.nameTitle = nameTitle
        self.nameDetail = nameDetail
    }

    var titleFirstLetter: String {
        return String(self.nameTitle[self.nameTitle.startIndex]).uppercased()
    }
}

class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView?

    var names: [Name] = []

    var sortedFirstLetters: [String] = []
    var sections: [[Name]] = [[]]

    override func viewDidLoad() {
        super.viewDidLoad()

        let cell001 = Name(nameTitle: "Acker", nameDetail: "Details for Acker are listed here.")
        names.append (cell001)

        let cell002 = Name(nameTitle: "Baker", nameDetail: "Details for Baker are listed here.")
        names.append (cell002)

        let cell003 = Name(nameTitle: "Caker" , nameDetail: "Details for Caker are listed here.")
        names.append (cell003)

        let cell004 = Name(nameTitle: "Dacker", nameDetail: "Details for Dacker are listed here.")
        names.append (cell004)

        let cell005 = Name(nameTitle: "Ecker", nameDetail: "Details for Ecker are listed here.")
        names.append (cell005)

        let cell006 = Name(nameTitle: "Facker", nameDetail: "Details for Facker are listed here.")
        names.append (cell006)

        let firstLetters = names.map { $0.titleFirstLetter }
        let uniqueFirstLetters = Array(Set(firstLetters))

        sortedFirstLetters = uniqueFirstLetters.sorted()
        sections = sortedFirstLetters.map { firstLetter in
            return names
                .filter { $0.titleFirstLetter == firstLetter }
                .sorted { $0.nameTitle < $1.nameTitle }
        }
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sortedFirstLetters[section]
    }

    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return sortedFirstLetters
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let name = sections[indexPath.section][indexPath.row]

        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = name.nameTitle
        cell.detailTextLabel?.text = name.nameDetail

        return cell
    }
}

这篇关于如何使用自定义模型类按节按字母顺序对tableView中的数据进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆