arrays - 多个数组提供 UICollectionView 数据源

标签 arrays swift uicollectionview

我有一个自定义类的数组,用于填充 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/

相关文章:

compare - 在 Swift 中比较字符

ios - UICollectionViewFlowLayout 的行和列

c++ - 将 char 数组转换为 uint8_t

python - np.array[ :, 0] 和 np.array[ :, [0]] 有什么区别?

c - 将 PORTD 值存储在 pic18f452 的数组中 (C)

C 程序 - 使用或不使用指针正确初始化和打印字符数组?

swift - 绕过 Firebase 创建的唯一自动 ID。 swift 3.0

swift - NSURLSession 初始化错误

ios - 通过storyboards在同一个UICollectionView中注册多个header supplementary view

ios - 关闭已用时间