我试图首先在集合视图中显示变量carmaker的列表,然后当用户从第一个集合视图中点击Honda时,它会将列表更改为变量Honda。每次我从下面运行代码时都会给我一个错误"致命错误:索引超出范围"错误来自
cell.title.text = Honda[indexPath.row]
我不明白为什么,因为它与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")
}
}
答案 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()
}
答案 1 :(得分:0)
它超出了范围,因为数组是零索引的,这意味着你的数组中有4个项目是索引0,1,2,3。索引4没有项目,因为它是第5个项目本田阵列。