从JSON Data Swift 4创建TableView节 [英] Creating TableView Sections from JSON Data Swift 4

查看:57
本文介绍了从JSON Data Swift 4创建TableView节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON数据文件已经按字母顺序排列,并正确显示在TableView中.我使用以下方法设置了板块标题:

My JSON data file is already alphabetized and is properly showing in my TableView. I set up my section titles using:

struct FigureStats: Decodable {
let name: String
let number: String
let year: String?
}

var figSectionTitles = [String]()
var figures = [FigureStats]()

override func viewDidLoad() {
super.viewDidLoad()
figSectionTitles = [String](arrayLiteral: "#", "A", "B", "C")
}

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

func tableView( tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return figures.count
}  

func downloadJSON(completed: @escaping () -> ()) {
    let url = URL(string: "https://xxxx")

    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error == nil {
            do {
                self.figures = try JSONDecoder().decode([FigureStats].self, from: data!)
                DispatchQueue.main.async {
                    completed()
                }
            } catch {
                print("JSON Error")
            }
        }
    }.resume()
}

问题是所有条目都在每个部分中重复出现,而不是根据每个名称的第一个字符落在正确的部分之下.

The problem is all of the entries are repeated inside each section instead of falling under the correct section based on the first character of each name.

如何获取每个名称的第一个字符,然后将这些条目归入正确的部分?

How can get the first character of each name and then get those entries to fall under the correct section?

推荐答案

您可以使用

You can use init(grouping:by:) to group the array into Dictionary.

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var figures = [Employee]()
var figuresByLetter = [(key: String, value: [Employee])]()
override func viewDidLoad() {
    super.viewDidLoad()
    figures = [Employee(name: "Kofi", year: 2000, id: 1),Employee(name: "Abena", year: 2002, id: 2),Employee(name: "Efua", year: 2003, id: 3),Employee(name: "Kweku", year: 2003, id: 3),Employee(name: "Akosua", year: 2003, id: 3)]
    figuresByLetter = Dictionary(grouping: figures, by: { String($0.name.trimmingCharacters(in: .whitespaces).first!) }).sorted(by: { $0.0 < $1.0 })
    print(figuresByLetter)
}
func numberOfSections(in tableView: UITableView) -> Int {
    return figuresByLetter.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return figuresByLetter[section].key
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return figuresByLetter[section].value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
    cell.textLabel?.text = figuresByLetter[indexPath.section].value[indexPath.row].name
    return cell
}


}
struct Employee {
    var name:String?
    var year:Int?
    var id:Int?
}

分组后的数据

[(key: "A", value: [Employee(name: "Abena", year: 2002, id: 2), Employee(name: "Akosua", year: 2003, id: 3)]),
 (key: "E", value: [Employee(name: "Efua", year: 2003, id: 3)]),
 (key: "K", value: [Employee(name: "Kofi", year: 2000, id: 1), Employee(name: "Kweku", year: 2003, id: 3)])]

这篇关于从JSON Data Swift 4创建TableView节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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