单击前一个值时更改 uicollectionview numberofsection

change uicollectionview numberofsection when previous value clicked

我试图首先在集合视图中显示变量汽车制造商的列表,然后当用户从第一个集合视图中单击本田时,它会将列表更改为变量本田。每次我 运行 下面的代码都会给我一个错误 "fatal error: Index out of range" 错误来自 cell.title.text = Honda[indexPath.row] 我不明白为什么,因为它与 Honda.count

具有相同的值 (4)
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")
    }

}

您应该在更改数据源时重新加载数据,在您的例子中是在 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()
}

它超出了范围,因为数组是零索引的,这意味着其中有 4 个项目的数组是索引 0、1、2、3。索引 4 处没有项目,因为那是第 5 个项目在本田阵列中。