如何解决如何使用 MVC 检索 UICollectionView 中 2 个不同部分的数据
大家好,我的 ios 项目中的每个人我正在使用 MVC 来管理必须显示预定义时间的 dill
。
此 collectionView
有两个部分,我需要在一个部分中显示一些特定数据,而在另一部分中显示其他数据
我需要帮助..我有一个结构模型
collectionView
我以这种方式恢复数据,因为我需要查看 struct TimeSelModel {
let hour: String
let minute: String
}
部分 0 中的一些数据和部分 1 中的其他数据
collectionview
我在控制器内部以这种方式使用数据
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 的 2 个不同部分显示不同数据的目标?
解决方法
您需要一个真正的多维数据模型,这可以是嵌套数组,但最好使用包装结构。如果您需要部分标题名称,只需取消对 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,它非常强大
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。