从indexpath.row中的数组中获取特定值

时间:2016-10-05 18:24:34

标签: arrays swift

我想从汽车制造数组中获取第二个和第三个值并返回下面的函数。我试过了 cell.title.text = carmake[1...2][indexPath.row]cell.title.text = carmake[indexPath.[1...2]],但没有一个是正确的。请帮帮我

carmake = ["hi","hello","how are you","i am good"]

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell

  cell.title.text = carmake[indexPath.row]
  return cell
}

2 个答案:

答案 0 :(得分:0)

如果要将它们组合起来,可以尝试:

cell.title.text = carmake[1] + carmake[2]

答案 1 :(得分:0)

如果你想在集合视图中只返回数组中的第二个和第三个项目,那么你应该尝试:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    //returns number of sections in collectionview, which in your case seems to be 1
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    //returns number of items per section, which in your case, you have stated is 1
    return 1

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell
    //indexpath.item starts at 0. indexPath.item + 1 and + 2 because you want to return carMake[1] and carMake[2].
    cell.title.text = carmake[indexPath.item + 1] + carmake[indexPath.item + 2]

    return cell
}