arrays - 从数组中获取特定值以返回 NSIndexpath.row

标签 arrays swift collectionview

我希望我的 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/

相关文章:

ios - 我们可以指定可以在 Collection View 的每个部分中显示的行数吗

ios - 如何使用 UICollectionView 使用 SDWebImage 添加溶解动画

javascript - 请解释一下这个函数.reduce是如何工作的

c - 超出范围时 undefined variable

arrays - 如何访问子例程返回的列表的最后一项而不先将其复制到数组中?

ios - Swift:如何返回类<UITableViewDataSource>?

java - 对任何类型的对象进行排序,java

ios - Swift Tableview 获取特定单元格不工作

swift - 如何在每行 2 个单元格的 Collection View 单元格中设置内部间距?

swift - 在我的准备 segue 函数中,数据没有在正确的时间传输