首页 > 解决方案 > 如何填充在其行中嵌入了 collectionViews 的 tableView 并按类型或类别组织它们?

问题描述

我有一个事件/场地管理应用程序和一个视图接收 json 格式的事件数据,其中每个事件都有一个类别或类型。如何填充和组织嵌入在 TableView 单元格中的 collectionViews 中的事件,其中每个 TableView 单元格都是要显示的类别或类型。如果可能的话,用 Swift 回答

标签: iosswiftgoogle-cloud-firestorealamofire

解决方案


创建具有所有可用属性的结构并为类别添加枚举

struct Event {
    enum Category {
        case a
        case b
        case c
    }
    var category: Category
    var eventName: String
    //...
}

创建 Event 对象的二维数组

var groupedEventsArr = [[Event]]()

从服务器接收到数据后,创建一个 Event 对象数组。

let eventsArr:[Event] = //json parse

然后根据数组对象分组category

groupedEventsArr = Array(Dictionary(grouping: eventsArr, by: { $0.category }).values)

现在在tableview中使用这个数组,collection view数据源方法

//表格视图

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return groupedEventsArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    let category = groupedEventsArr[indexPath.row].first?.category
    return cell!
}

//集合视图

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return groupedEventsArr[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    let event = groupedEventsArr[indexPath.section][indexPath.item]
    return cell
}

推荐阅读