【问题标题】:tapping on collection view item causes multiple selection in collection view, instead of single selection点击集合视图项目会导致集合视图中的多选,而不是单选
【发布时间】:2016-11-19 08:14:19
【问题描述】:

我有一个UICollectionView 和一个自定义单元格。自定义单元格包含一个UIImageView 和一个UILabel

  1. 我想更改UIImageView 的背景颜色,当我点击相应的单元格时(在didSelectItemAt indexPath 方法中我想访问自定义单元格属性)。有没有办法实现这一目标?还是我需要一些替代方法?
  2. 我遇到的另一个问题是,当我从该UICollectionView 中点击任何项目时,会发生多项选择。意味着可重复使用的单元格也会被选中。

谁能帮帮我?

【问题讨论】:

  • 你在 swift 中工作吗?
  • 是的,我正在使用 swift。

标签: ios swift


【解决方案1】:

试试这个:

1.自定义UICollectionViewCell 类:

import UIKit

class CustomCollectionViewCell: UICollectionViewCell
{
    //MARK: Outlets
    @IBOutlet weak var testImageView: UIImageView!
    @IBOutlet weak var testLabel: UILabel!

    //MARK: Lifecycle Methods
    override func awakeFromNib()
    {
        self.testImageView.image = nil
        self.testLabel.text = nil
    }

    override var isSelected: Bool{
        willSet{
            super.isSelected = newValue
            if newValue
            {
                self.backgroundColor = UIColor.lightGray
            }
            else
            {
                self.backgroundColor = UIColor.groupTableViewBackground
            }
        }
    }
}

2。实现UICollectionViewDelegate方法为:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredVertically)
}

您可以根据需要更改单元格选择和默认颜色。

【讨论】:

    【解决方案2】:

    第一个问题

    请参阅this 链接,因为它包含有关如何访问单元格及其属性的说明。 (它适用于UITableView,但同样的事情也适用于UICollectionView

    第二个问题

    您必须在didSelectRowcellForRowAtIndexPath 上更新您的模型,您必须根据该模型设置单元格的颜色。

    第二点的另一个解决方案是将选定的 indexPath 存储在 数组并在您的cellForRowAtIndexPath 中检查indexPath 存在于该数组中并适当地设置其颜色。示例:

    var array = [Int]()
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
          //update model or
          array.append(indexPath.item)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //check model or
        if(array.contains(indexPath.item)){
    
    
        }else{
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      相关资源
      最近更新 更多