2016-10-04 34 views
-1

我想在第一個集合視圖中顯示變量carmaker的列表,然後當用戶從第一個集合視圖點擊本田時,它會將列表更改爲變量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

我讀了你的評論,並嘗試把'case'後面的self.collectionView.reloadData()本田「:'在numberofsection和cellforitematindexpath函數,但我仍然得到相同的錯誤 – 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沒有項目,因爲這會是本田陣列中的第五項。

+0

由4我的意思是有4個值內的數組。 honda [indexpath.row]和honda.count都有4個項目。 – freelixa