如何使用 MVC 检索集合视图中 2 个不同部分的数据

How to retieve data for 2 different section in UICollectionView using MVC

大家好,我的 ios 项目中我正在使用 MVC 来管理必须显示预定义时间的 collectionView

这个 collectionView 有两个部分,我需要在一个部分显示一些特定数据,在另一个部分显示其他数据

我需要帮助..我有一个结构模型

struct TimeSelModel {
    let hour: String
    let minute: String
}

我以这种方式恢复数据,因为我需要查看 collectionview 部分 0 中的一些数据和部分 1

中的其他数据
struct TimeSelData {
    
    static func dataSec (section: Int, _ completion: @escaping (Result <[TimeSelModel], Error>) -> ()) {
            if section == 0 {completion (.success (dataSec0))}
            else {completion (.success (dataSec1))}
    }
}
    
let dataSec0 = [
    TimeSelModel (hour: "09", minute: ": 30"),
    TimeSelModel (hour: "17", minute: ": 00")
]

let dataSec1 = [
    TimeSelModel (hour: "12", minute: ": 00"),
    TimeSelModel (hour: "19", minute: ": 00")
]

我在控制器中以这种方式使用数据

private var section: Int = 0

var data: [TimeSelModel] = []

private func fetchData() -> Void {
        
        TimeSelData.dataSec(section: section) {(result) in
            
            switch result {
            
            case.success (let data):
                
                self.data = date

            case.failure (let error): print (error.localizedDescription)

            }
        }
    }

    func collectionView (_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.section = section
        return data.count}
    
    func collectionView (_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell (withReuseIdentifier: TimeSelCell.cellID, for: indexPath) as! TimeSelCell
        
        cell.dataModel = data[indexPath.item]

        return cell
    }

它不起作用我没有为我的 collectionView 的部分获取正确的数据...我怎样才能实现为 collectionView 的 2 个不同部分显示不同数据的目标?

您需要一个真正的多维数据模型,这可以是嵌套数组,但最好是包装器结构。如果您需要 header 部分的名称,只需取消注释 name 成员即可。

不需要TimeSelData结构,转义闭包无论如何都没有意义

struct Section {
    // let name : String
    let models : [TimeSelModel]
}


var data: [Section] = []

private func fetchData() {
    data = [Section(models: dataSec0), Section(models: dataSec1)]
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return data.count
}
    
func collectionView (_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return data[section].models.count
}

func collectionView (_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell = collectionView.dequeueReusableCell (withReuseIdentifier: TimeSelCell.cellID, for: indexPath) as! TimeSelCell
    
    cell.dataModel = data[indexPath.section].models[indexPath.item]

    return cell
}

换用UICollectionViewDiffableDataSource,很强大