当单击添加/删除数组时,Swift Collection视图didSelectItemAtIndexPath

时间:2016-08-17 08:03:20

标签: ios arrays swift uicollectionview

我有swift集合视图并有项目,我想添加每个项目点击到数组和相同的项目再次点击将被删除数组。我的代码在这里。

我的阵列

var services = [""]

我的didSelectItemAtIndexPath代码

   func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {


           let clickeditem = items[indexPath.section].services[indexPath.item - 1]
                print(clickeditem) // here clicked item this item will be add to services array when first click, after clicked again will be remove in services array


    }
  

clickeditem //将在第一次点击时添加到services数组,再次点击后将在服务数组中删除

1 个答案:

答案 0 :(得分:1)

您可以使用结构,所以:

struct Item {
    let indexPath: NSIndexPath 
    let value: AnyObject
}

services.append(Item(indexPath, value: clickeditem))

然后删除你可以使用该indexPath迭代并检查元素:

for item in services {
    if item.indexPath == indexPath {
        //remove your item and whatever you want
    }
}