【问题标题】:tableview expand collapse issue with JSON Data使用 JSON 数据的 tableview 展开折叠问题
【发布时间】:2020-12-22 13:34:13
【问题描述】:

我正在创建Swift 应用程序和内部应用程序我正在实现UITableView 折叠/展开功能,我正在表格视图中设置静态数据并成功显示,但是当我尝试加载JSON 时,我面临的问题这是我的代码和模型结构

这里是要解析的模型JSON

public struct Item {
    var service: String
    var service_price: Int
    var barber_service_id: Int
    var service_duration: Int
    
    public init(service: String, service_price: Int,barber_service_id: Int,service_duration: Int) {
        self.service = service
        self.service_price = service_price
        self.barber_service_id = barber_service_id
        self.service_duration = service_duration
    }
}
public struct Section1 {
    var name: String
    var items: [Item]
    var collapsed: Bool
    
    public init(name: String, items: [Item], collapsed: Bool = false) {
        self.name = name
        self.items = items
        self.collapsed = collapsed
    }
}

这是我用静态数据填充 tableview 的方式

public var sectionsData: [Section1] = [
    Section1(name: "Beard", items: [Item(service: "Beard Trim", service_price: 1, barber_service_id: 1, service_duration: 30),Item(service: "Beard Line Up", service_price: 1, barber_service_id: 1, service_duration: 30)], collapsed: true)
]

正如你可以在静态代码中看到的那样,我在 Item 数组中添加了两项,现在这是我尝试使用 JSON 数据实现的代码

service.array?.forEach({ (sList) in
       let item = Item(service: sList["service"].stringValue, service_price: sList["service_price"].intValue, barber_service_id: sList["barber_service_id"].intValue, service_duration: sList["service_duration"].intValue)
       let sections = Section1(name: category_name, items: [item], collapsed: true)
       self.sections.append(sections)
})

正如您在我的代码中看到的,我为每个循环获取 JSON 数据,但现在在静态代码中我能够添加多个项目,因此在动态数据中如何执行此操作

谁能帮我解决这个问题

【问题讨论】:

    标签: ios json swift uitableview collapse


    【解决方案1】:

    创建一个实例变量来保存您的数据源。

    var sectionsData: [Section1] = []
    

    从 API 响应创建部分

    guard let array = service.array else {
        return
    }
    
    let newSections: [Section1] = array.map { (sList) in
        let item = Item(service: sList["service"].stringValue, service_price: sList["service_price"].intValue, barber_service_id: sList["barber_service_id"].intValue, service_duration: sList["service_duration"].intValue)
        return Section1(name: category_name, items: [item], collapsed: true)
    }
    

    将此新数据添加到您的实例变量中

    sectionsData.append(contentsOf: newSections)
    

    重新加载表数据(在主线程上)

    【讨论】:

    • 谢谢,但在尝试您的代码Generic parameter 'T' could not be inferred 后出现错误,请参阅我已在出现错误的地方编辑了您的答案
    • 对不起,我在stackoverflow上写了这段代码。为 newSections 添加类型。我会更新代码。
    • 好的,我正在尝试搜索但无法解决此错误,请帮助我
    • 我再次收到此错误Value of optional type '[Section1]?' must be unwrapped to a value of type '[Section1]'
    • 使用地图Cannot convert value of type 'Int' to expected argument type 'String'后也出现此错误
    猜你喜欢
    • 1970-01-01
    • 2013-07-14
    • 2016-08-25
    • 2023-03-20
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多