我有一个自定义类的数组,用于填充 UICollectionView。
从其他 iOS 设备(通过 Multipeer Connectivity)接收到相同自定义类的其他数组。数据对象包含在类类型中,因此非常大,我不想复制和我当前的逻辑,我正在考虑将它们保留在单独的数组中。
考虑到这一点,我该如何管理 UICollectionView 委托(delegate)方法?
项目计数建议。假设第二个数组在 MPC 发送它的数据之前是空的,它的计数将为 0:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array1.count + array2.count
}
如何在两个数组之间控制 cellForItemAt 中的 indexPath?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
if indexPath.item < array1.count {
cell.labelTitle.text = array1[indexPath.item].title
} else {
// IS THIS RIGHT, AS CALCULATED INDEXPATH?
if array2 != nil {
cell.labelTitle.text = array2[indexPath.item - array1.count].title
}
}
return cell
}
或者这是完全错误的方法?这似乎更难管理...
最佳答案
您可以使用辅助计算属性:
var totalArray: [OriginalContentType] { return array1 + array2 }
然后像平常一样对待它。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return totalArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
cell.labelTitle.text = totalArray[indexPath.item].title
}
关于arrays - 多个数组提供 UICollectionView 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57598231/