freelixa freelixa - 1 month ago 5
Swift Question

change uicollectionview numberofsection when previous value clicked

I'm trying to show the list of variable carmaker in collection view at first then it will change the list into variable Honda when users click on Honda from the first collection view. every time i ran the code from below it give me an error "fatal error: Index out of range" the error come from

cell.title.text = Honda[indexPath.row]
i do not understand why because it has the same value (4) with
Honda.count


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")
}

}

Answer

You should reload the data when you change the data source, in your case at the end of the didSelectItemAtIndexPath method.

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()
}
Comments