简体   繁体   English

单击时的Swift集合视图didSelectItemAtIndexPath单击添加/删除数组

[英]Swift Collection view didSelectItemAtIndexPath when clicked add / remove in array

I have swift collection view and have items , i want to add each item clicked to array and same item when clicked again will be remove in array. 我有快速收集视图并有项目,我想将单击的每个项目添加到数组,再次单击相同的项目将在数组中删除。 My codes here. 我的代码在这里。

My array 我的数组

var services = [""]

My didSelectItemAtIndexPath codes 我的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 // will be add to services array when first click, after clicked again will be remove in services array clickeditem //将在第一次单击时添加到服务数组,再次单击后将在服务数组中删除

You could use a struct, so: 您可以使用结构,因此:

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

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

and then to remove you can iterate and check the element with that indexPath: 然后要删除,您可以迭代并检查带有该indexPath的元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 didSelectItemAtIndexPath在集合视图Swift中不起作用 - didSelectItemAtIndexPath Doesn't Work In Collection View Swift 在容器视图中的容器视图中显示视图控制器 didSelectItemAtIndexPath swift - Present view controller in a container view at collection view didSelectItemAtIndexPath swift 某些收集视图单元的didSelectItemAtIndexPath不起作用 - some of the collection view cell didSelectItemAtIndexPath not working Swift-想要在集合视图单元格中单击按钮时进行更改 - Swift - want to make changes when a button clicked which is inside a collection view cell (快速)在外部视图中定义的UICollectionView中的didSelectItemAtIndexPath不起作用 - (Swift) didSelectItemAtIndexPath in UICollectionView defined in external view doesn't work 在Swift中删除集合视图中的额外空间 - Remove Extra Space in Collection View in Swift 使用页面控件(Swift)在集合视图/轮播视图上滑动时删除水平线 - Remove horizontal line when swiping across a collection view / carousel view with page control (Swift) didSelectItemAtIndexPath没有在ios swift中调用 - didSelectItemAtIndexPath is not calling in ios swift Swift Collectionview didSelectItemAtIndexPath不起作用 - Swift Collectionview didSelectItemAtIndexPath not working Swift:单击按钮时删除背景色 - Swift: remove background color when button clicked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM