2016-10-05 13 views
2

私のコレクションビューで特定の配列だけを返すようにしたい。私はそれが "AUDI"から "Chevrolet"または[2 ... 9]にしか戻らないようにしたい。車のメイクと新車の配列を作る、両方とも8の値を持っている。彼らは両方が同じでなければならないが、私にエラーfatal error: Index out of boundsを与える。私は何を間違えたのですか?NSIndexpath.rowで返す配列から特定の値を取得

var car make = ["Honda","Toyota","AUDI","Bentley","BMW","Mercedes","Buick","Cadillac","KIA","Chevrolet","Corvette","Dodge","FIAT","Ford","GMC","Hyundai","Infiniti","Jaguar","JEEP","LandRover","LEXUS","Mazda","Nissan","RAM","Porsche","Scion","Volkswagen"] 

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

      return carmake[2...9].count 
    } 

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
     let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell 

      let newcarmake = carmake[2...9] 
      cell.title.text = newcarmake[indexPath.row] 
     return cell 
    } 
+0

ヒント: '2..8'対' 2.9'。 – rmaddy

+0

申し訳ありませんが、タイプミスでした。私はそれを[2 ... 9]に変更します。それでも同じエラーが発生する – Alan

答えて

2

carmake[2...9]アレイしかしArraySliceなく、アレイ・スライスは、それらがから作成されていることアレイと同じインデックスを使用 。 carmake[2...9]の有効なインデックスは2...9で、0...7 ではありません。

一つの解決策ではなく、実際の配列を作成するために、次のようになります。

let newcarmake = Array(carmake[2...9]) 
cell.title.text = newcarmake[indexPath.row] 

はまた、

cell.title.text = carmake[indexPath.row + 2] 
+1

あなたは命を救っています。私はどこでも探しています – Alan

0

問題があなたのNSIndexPathであり、たとえば、簡単な オフセット計算で元の配列を参照します。 あなたのコードはほぼ良好です。それは少し変更が必要です。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell 

    cell.title.text = carmake[indexpath.row + 2] 
    return cell 
} 

​​は、配列ではなくテキストです。そのコードを試してください。