从JSON Data Swift 4创建TableView部分

时间:2018-05-19 17:23:35

标签: ios json swift

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

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()
}

问题是所有条目都在每个部分内重复,而不是根据每个名字的第一个字符落在正确的部分下。

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

2 个答案:

答案 0 :(得分:3)

您可以使用init(grouping:by:)将数组分组为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)])]

enter image description here

答案 1 :(得分:0)

func numberOfSections(in tableView: UITableView) -> Int {
    return figuresByLetter.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let sectionTitle = figuresByLetter[indexPath.section]
    return sectionTitle 
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionTitle = figuresByLetter[indexPath.section]
    //filteredArray = filter the array of figures based on current section value
    return filteredArray.count
}