我有一个由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" ]
我为单元格创建了一个UITapGesture识别器,当我单击单元格时,我得到了索引。
这是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] 如果我按下第 4 部分的第 2 项(即芒果)。但是我不知道如何翻译索引,以获取相应的字符串值。我的意思是这样的:
var itemName:String=[2,4](itemName将为mango)
我是swift新手,因此任何帮助都将是巨大的。
非常谢谢。
您需要的是一个数组,也称为2D数组-[[String]]
。
var array = [picList, vehicleList, fruitsList, bodyPartsList]
然后,您可以使用 2 个索引访问它,如下所示:
var itemName = array[2][4]
您可以创建一个二维数组,并在那里添加您的列表,indexpath.section 将是列表的索引,indexpath.item 将是 thst 列表中的索引