我希望我的集合视图只返回特定的数组。我希望它只能从“奥迪”返回到“雪佛兰”或[2 ... 9]。汽车制造和新车制造阵列,都有8的值。他们都应该是相同的,但它给我错误fatal error: Index out of bounds
。我做错了什么??
var car make = ["Honda","Toyota","AUDI","Bentley","BMW","Mercedes","Buick","Cadillac","KIA","Chevrolet","Corvette","Dodge","FIAT","Ford","GMC","Hyundai","Infiniti","Jaguar","JEEP","LandRover","LEXUS","Mazda","Nissan","RAM","Porsche","Scion","Volkswagen"]
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return carmake[2...9].count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell
let newcarmake = carmake[2...9]
cell.title.text = newcarmake[indexPath.row]
return cell
}
答案 0 :(得分:2)
carmake[2...9]
不是数组,而是ArraySlice
和数组切片
使用与创建它们的数组相同的索引。
因此carmake[2...9]
的有效索引为2...9
,而不是0...7
正如你所预料的那样。
一种解决方案是创建一个真正的数组:
let newcarmake = Array(carmake[2...9])
cell.title.text = newcarmake[indexPath.row]
或者,用简单的方法引用原始数组 偏移计算,例如
cell.title.text = carmake[indexPath.row + 2]
答案 1 :(得分:0)
问题在于您的NSIndexPath
。
你的代码差不多好。它需要一点改变。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell
cell.title.text = carmake[indexpath.row + 2]
return cell
}
newCarMake
是一个文本,而不是数组。试试那段代码。