我希望我的 Collection View 仅返回特定的数组。我希望它仅从“AUDI”返回到“Chevrolet”或[2...9]。汽车品牌和新车品牌数组的值都是 8。它们应该是相同的,但它给我错误 fatal error :索引超出范围
。我做错了什么??
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
}
最佳答案
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]
关于arrays - 从数组中获取特定值以返回 NSIndexpath.row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882800/