2016-10-04 7 views
-1

私は最初にコレクションビューで変数carmakerのリストを表示しようとしていますが、最初のコレクションビューからHondaをクリックすると、リストが変数Hondaに変わります。 「致命的なエラー:インデックス範囲外」私はそれは私にエラーを与えるの下からのコード実行するたびに私は理解していない cell.title.text = Honda[indexPath.row]から来るエラーをなぜそれがと同じ値(4)があるためHonda.count前の値がクリックされたときにuicollectionview numberofsectionが変更されます

var selectedrow = 0 
var choice1 = "" 
var choice2 = "" 

// car make 
var carmake = ["Honda","Toyota","AUDI","Bentley","BMW","Mercedez","Buick","Cadillac","KIA","Chevrolet","Corvette","Dodge","FIAT","Ford","GMC","Hyundai","Infiniti","Jaguar","JEEP","LandRover","LEXUS","Mazda","Nissan","RAM","Porsche","Scion","Volkswagen"] 
// car model 
var Honda = ["Oddyssey","Civic","Fit","Adam"] 


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    switch choice1 { 
    case "Honda": 
     let hon = Honda.count 
     print(hon) 
     return Honda.count 
    default: 
     print("default") 
     return carmake.count 
    } 
} 

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell 
    switch choice1 { 
    case "Honda": 
     //let number = Honda[indexPath.row] 
     //print(number) 
     cell.title.text = Honda[indexPath.row] 
    default: 
     cell.title.text = carmake[indexPath.row] 
    } 
    return cell 
} 

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    selectedrow = indexPath.row 

    switch carmake[selectedrow] { 
    case "Honda": 
     print("honda") 
     choice1 = "Honda" 
     print(choice1) 
    default: 
     print("none selected") 
    } 

} 
+0

ここで、コレクションビューをリロードしますか? –

+0

あなたのコメントを読んで、numberofsectionとcellforitematindexpath関数の両方で 'case" Honda ":'の後にself.collectionView.reloadData()を置こうとしましたが、まだ同じエラーが発生します – freelixa

+0

これらのメソッドでデータをリロードしないでください。どこに元々置いたのですか? –

答えて

0

didSelectItemAtIndexPathメソッドの最後に、データソースを変更する際にデータをリロードする必要があります。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    selectedrow = indexPath.row 

    switch carmake[selectedrow] { 
    case "Honda": 
     print("honda") 
     choice1 = "Honda" 
     print(choice1) 
    default: 
     print("none selected") 
    } 
    self.collectionView.reloadData() 
} 
+0

ありがとうSam。あなたは私の人生を救う:) – freelixa

+0

あなたは大歓迎です:) –

0

配列がその中に4つの項目とあなたの配列を意味し、インデックス付きゼロであるため、それが範囲外起こっているのは、インデックス0、1、2、3であることが可能だろうと何の項目は、インデックス4ではありませんホンダの配列の5番目の項目。

+0

私はその配列内に4つの値があることを意味しました。ホンダ[indexpath.row]とhonda.countの両方に4つの項目があります。 – freelixa

関連する問題