从数组获取特定值到 NSIndexpath.row 中的 return

get specific value from array to return in NSIndexpath.row

我希望我的集合视图 return 仅特定数组。我希望它 return 仅从 "AUDI" 到 "Chevrolet" 或 [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
    }

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]

您的 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 是文本,不是数组。试试那个代码。