如何在Swift中使用3d数组作为UICollectionView的数据源?

时间:2015-02-24 11:04:42

标签: ios swift multidimensional-array uicollectionview

我有一个三维数组的数据源。

我使用第一个维度计数作为节数。

我使用第三维作为每个部分中的项目。

以下是一些示例数据:

let sentence1 = [word1, word2, word1] // These are Word objects
let sentence2 = [word1, word2, word3] // in my model.
let sentence3 = [word4, word5, word3]

let paragraph1 = [sentence1, sentence2] // These are Sentence objects.
let paragraph2 = [sentence1, sentence3]

let article = [paragraph1, paragraph2]

目前我刚制作了3dArray的副本并将第二维和第三维展平为一维,从而使三维数组成为二维数组。然后我返回new2dArray.count作为numberOfSectionsInCollectionView并在cellForItemAtIndexPath中制作单元格,如下所示:

let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as UICollectionViewCell

let cellLabel = new2dArray[indexPath.section][indexPath.row]

但是,在我的didSelectItemAtIndexPath中,我需要访问3dArray的第二维。我正在寻找这样的东西:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    println("did select cell \(indexPath.row) inside of \(secondDimension) inside of \(indexPath.section)")

我需要做什么?

2 个答案:

答案 0 :(得分:1)

这就是我解决这个问题的方法:

  1. 将3d数组部分展平为2d数组,可用作集合视图的数据源。
  2. 如果该数组也被展平,则查找twoDimensionalArray [indexPath.section] [indexPath.row]的索引。 (https://stackoverflow.com/a/28742108/538034
  3. 计算threeDimensionalArray中的许多元素,然后像这样保存各个索引:

    func find3dIndex(article: Array<Array<Array<String>>>, flatWordIndex: Int) -> (Int, Int, Int) {
            var fullSentenceArray = [String]()
            var counter = 0
    
            for index in 0...flatWordIndex {
                for (paragraphIndex, paragraph) in enumerate(article) {
                    for (sentenceIndex, sentence) in enumerate(paragraph) {
                        for (wordIndex,word) in enumerate(sentence) {
                            if counter == flatWordIndex {
                                println("tuple: \(paragraphIndex), \(sentenceIndex), \(wordIndex)")    
                                return (paragraphIndex, sentenceIndex, wordIndex)    
                                break
                            }
                            counter += 1
                        }
                    }
                }
            }
        return (99,99,99)
     }
    

答案 1 :(得分:0)

继续我的评论之后,为什么不尝试一个字典数组,其中每个字典代表一个部分,在字典中你可以存储一个表示该部分中的行的数组。这是一些伪代码:

// The items in the array under 'kRowData' represent each individual cell, this maybe a value, a model object, or even another dictionary
let sectionOne = ["kRowData" : [1,2,3,4,5,6]]
let sectionTwo = ["kRowData" : [1,2,3,4,5,6]]
let sectionThree = ["kRowData" : [1,2,3,4,5,6]]

let sectionData = [sectionOne,sectionTwo,sectionThree]

sectionData.count // your number of sections
sectionData[indexPath.section]["kRowData"].count // your number of rows in section