UICollectionViewCell 快速选择多个单元格 [英] UICollectionViewCell Selecting multiple cells swift

查看:31
本文介绍了UICollectionViewCell 快速选择多个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个应用程序来选择多个单元格,所以假设我们有 9 个单元格索引从 0 到 8.

I'm trying to make an app to select multiple Cells, so let's assume we have 9 cells Indexed from 0 to 8.

这就是我想要做的......

Here is what i was trying to do...

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

var cell = collectionView.cellForItemAtIndexPath(indexPath)

   if cell?.selected == true {
    cell?.backgroundColor = UIColor.orangeColor()
   }

}

并取消选择 Func()

And Deselect Func()

    func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {        
       var cell = collectionView.cellForItemAtIndexPath(indexPath)
        cell?.backgroundColor = UIColor.clearColor()
    }

如果用户选择一个单元格就足够简单了 -> 如果取消选择一个单元格,则为橙色 -> clearColor 'white'所以是的,这段代码正在工作,除了

It's simple enough if a user selects a cell -> orange if deselects a cell -> clearColor 'white' So yea this code is working except

如果用户选择了单元格 0,它也会改变单元格 6 的颜色,请记住,单元格 6 没有被选中,它只是改变了它的外观".如果单元格 1 选择了单元格 7 更改等,则单元格 1 也是如此,如果我取消选择单元格 0 或单元格 6 都更改.

If a user selects cell 0, it also change the color of cell 6, "keep in mind cell 6 is not selected it just change it's appearance". Same for Cell 1 if it selected cell 7 changes and so on, also if i deselect either cell 0 or cell 6 both Changes.

所以我试过 cell?.selected == true, UICollectionView.allowsMultipleSelection = true 这两个属性对我都不起作用.

So i've tried cell?.selected == true, UICollectionView.allowsMultipleSelection = true both properties did not work for me.

我做错了什么吗?
这是一个与细胞重用有关的问题吗?如果可以,您能解释一下这种行为吗?

am i doing something Wrong ?
is it an issue related to Cell Reuse ? if so could you explain this behavior ?

推荐答案

这样做:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{
         var cell = collectionView.cellForItemAtIndexPath(indexPath)
         if cell?.selected == true {
            cell?.backgroundColor = UIColor.orangeColor()
         }
          else 
             cell?.backgroundColor = UIColor.clearColor()
}

还要为 UICollectionViewCell 创建一个自定义单元格.还要更改您的 cellForItemAtIndexPath 函数:

Also make a custom cell for UICollectionViewCell. Also change in your cellForItemAtIndexPath function :

if cell?.selected == true 
      cell?.backgroundColor = UIColor.orangeColor()
    else 
       cell?.backgroundColor = UIColor.clearColor()

这篇关于UICollectionViewCell 快速选择多个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆