【问题标题】:Getting values in double array from index. Swift从索引中获取双精度数组中的值。迅速
【发布时间】:2017-11-05 13:19:34
【问题描述】:

我有一个由 4 个部分组成的集合视图。

每个部分都是一个字符串数组,如下所示:

var picList: [String] = ["Bird", "Cat", "Cow", "Dog", "Duck", "Elephant", "Fish", "Giraffe", "Lion", "Mouse", "Sheep", "Snake" ]

var vehiclesList: [String] = ["Airplane", "Ambulance", "Boat", "Bus", "Car", "Fire_Engine", "Helicopter", "Motorcycle", "Tank", "Tractor", "Train", "Truck" ]

var fruitsList: [String] = ["Apple", "Banana", "Grapes", "Mango", "Orange", "Peach", "Pineapple", "Strawberry", "Watermelon" ]

var bodyPartsList: [String] = ["Arm", "Ear", "Eye", "Face", "Feet", "Hand", "Hair", "Legs", "Mouth", "Nose" ]

我为单元格创建了一个 UITapGestureRecognizer,当我单击单元格时,我会得到索引。

这里是tapMethod

func handleTap(sender: UITapGestureRecognizer) {
        print("tap")

        if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {

            let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

            print("index path: + \(indexPath)")


        } else {
            print("")
        }


    }

现在索引打印如下 [0,0](如果我按第一项,即鸟)。 [2,4] 如果我按下第 2 节中的第 4 项(即芒果)。但我不知道如何翻译索引,以获得相应的字符串值。我的意思是这样的:

var itemName: String = [2,4] (并且 itemName 是 mango)

我是 swift 新手,所以任何帮助都会很棒。

非常感谢。

【问题讨论】:

  • 其实[2,4]是第三部分的第五项;-)

标签: arrays swift


【解决方案1】:

您需要的是一个数组数组,也就是一个二维数组 - [[String]]

var array = [picList, vehicleList, fruitsList, bodyPartsList]

然后,您可以使用 2 个这样的索引来访问它:

var itemName = array[2][4]

【讨论】:

  • 谢谢。这正是我所需要的。
  • @ios234975 如果您认为我的回答回答了您的问题,请考虑接受!
【解决方案2】:

您可以创建一个二维数组,并在其中添加您的列表,indexpath.section 将是列表的索引,indexpath.item 将是第一个列表中的索引

【讨论】:

  • 谢谢。太好了,加上 Sweeper 的回答
猜你喜欢
  • 2015-02-03
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 2013-12-28
  • 2014-07-17
  • 2017-08-26
  • 1970-01-01
相关资源
最近更新 更多