JSON数据的tableview展开折叠问题

jvlzgdj9  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在创建Swift应用程序,并在应用程序内部实现UITableView折叠/展开功能,我正在tableview中设置静态数据并成功显示,但当我尝试加载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
    }
}

下面是用静态数据填充表视图的方法。

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

正如您在我代码中所看到的,我使用for each循环获取JSON数据,但现在在静态代码中,我可以添加多个项目,因此在动态数据中如何执行此操作
有人能帮我吗

kfgdxczn

kfgdxczn1#

创建一个示例变量来保存数据源。

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)

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

相关问题