Раздел и строка не отображаются должным образом в UITableView Swift - PullRequest
1 голос
/ 12 февраля 2020

Я пытаюсь реализовать разделы и строки в UITableView, но из-за вложенной JSON структуры модели мне не удается. Всегда печатать только first section title. Я использую Codable подход и структура модели не может быть изменена.

Как получить разделы и строки в tableView? Любое руководство или помощь будут очень благодарны. Я действительно борюсь за это.

  • Мне нужно отобразить в разделе tableView title и Rows textField - см. JSON.
  • прикрепленный скриншот, который печатает только один section title

Модель:

struct SectionList : Codable {

    let title : String?
    var items : [Item]?

}

struct Item : Codable {

    let actionType : Int?
    var textField : String?
    let pickList: [SectionList]?
    let itemValue: String?
    let version: Int?

}

Инициализация и код TableView:

var AppData: [Item]?

let decoder = JSONDecoder()
let response = try decoder.decode(SectionList.self, from: pickResult)
let res = response.items?.filter { $0.actionType == 101}
self.AppData = res


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

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
   return AppData?[section].pickList[0].title
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    let dic = AppData?[indexPath.section]//.pickList?[indexPath.row].title
        //AppData?[indexPath.section].pickList[indexPath.row].items
    //print(dic)

    return cell 
}

Ответы [ 2 ]

2 голосов
/ 12 февраля 2020

Все, что я понимаю под тобой, я делаю это. Проверьте этот код

Создать структуру как

struct SectionList : Codable {

    let title : String?
    var items : [RowItems]?

}

struct RowItems: Codable {
    var textField : String?
    let itemValue: String?
}

struct SourceData: Codable {
    let items: [Item]?
}
struct Item : Codable {
    let actionType : Int?
    let pickList: [SectionList]?
    let version: Int?

}

Создать переменную как

var AppData: Item?

Parse json как

let decoder = JSONDecoder()
            let response = try decoder.decode(SourceData.self, from: data)
            let res = response.items?.filter { $0.actionType == 101}
            print("jsonData:\(res)")
            AppData = res?.first

Источник данных таблицы вызовов как

func numberOfSections(in tableView: UITableView) -> Int {
    return AppData?.pickList?.count ?? 0
    }

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return AppData?.pickList?[section].items?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    let dic = AppData?.pickList?[indexPath.section].items?[indexPath.row]//.pickList?[indexPath.row].title
        //AppData?[indexPath.section].pickList[indexPath.row].items
    //print(dic)

    cell.textLabel?.text = dic?.textField
    return cell
}

Снимок экрана с этим кодом Table after this changes

0 голосов
/ 12 февраля 2020

ваша модель должна быть похожа на

import Foundation

    // MARK: - Items
    struct Items: Codable {
        let items: [ItemsItem]?
    }

    // MARK: - ItemsItem
    struct ItemsItem: Codable {
        let actionType, version: Int?
        let pickList: [PickList]?
    }

    // MARK: - PickList
    struct PickList: Codable {
        let title: String?
        let items: [PickListItem]?
    }

    // MARK: - PickListItem
    struct PickListItem: Codable {
        let textField, itemValue: String?
    }

ваша переменная должна быть такой

var appData : Items?

во время декодирования просто добавьте этот

appData = try decoder.decode(Items.self, from: pickResult)

ваш делегат представления таблицы и источник данных должен быть как

  func numberOfSections(in tableView: UITableView) -> Int {
                return appData?.items?.first?.pickList?.count ?? 1
            }
            func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
                let cell = UITableViewCell()
                return appData?.items?.first?.pickList?.first?.title
            }
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return appData?.items?.first?.pickList?[section].items?.count ?? 1
            }

            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = UITableViewCell()
                cell.textLabel?.text = appData?.items?.first?.pickList?.first?.items?[indexPath.row].textField
                return cell
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...