首页 > 解决方案 > 部分和行在 UITableView Swift 中未正确显示

问题描述

我正在尝试在 UITableView 中实现部分和行,但由于嵌套的 JSON 模型结构,我没有成功。它总是只打印first section title。我正在使用Codable方法,模型结构无法更改。

如何在 中实现部分和行tableView?任何指导或帮助将不胜感激。我真的为此而苦苦挣扎。

模型:

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 
}

标签: iosjsonswiftuitableview

解决方案


无论我怎么理解你,我都会做到。检查此代码

创建结构为

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?

将 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
}

此代码的屏幕截图 此更改后的表


推荐阅读