Создание разделов TableView из JSON Data Swift 4 - PullRequest
0 голосов
/ 19 мая 2018

Мой файл данных 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 голосов
/ 19 мая 2018
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
}
0 голосов
/ 19 мая 2018

Вы можете использовать init (группировка: по:) для группировки массива в словарь.

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...