关闭视图后如何保持集合视图单元格的状态?

Posted

技术标签:

【中文标题】关闭视图后如何保持集合视图单元格的状态?【英文标题】:How to maintain state of collection view cell after dismissal of view? 【发布时间】:2019-12-19 06:13:41 【问题描述】:

所以我有一个 collectionView,其中包含一系列趋势,用户可以单击以展示该照片。单击单元格时,会出现一个复选标记,让用户知道他们已选择该类别,然后将他们的 photoId 输入到数据库中选定的 childValues 中。

如果用户决定要从某个类别中删除他们的照片,他们可以选择编辑他们的照片。当我选择编辑个人资料时,应选择的单元格(我在上传照片时选择的单元格)未选中。

或者比如说,我已经上传了一张照片,但现在我想展示它,当我去编辑照片并点击一个类别时,会出现复选标记,告诉我这个类别已被选中。当我按保存时,照片会按预期添加到数据库中选择的 childValue 中,但是当我再次单击编辑配置文件并显示视图时。我 10 秒前选择的单元格现在未选中。

即使在关闭视图控制器后,我如何才能保持选中或取消选中状态?

   var selectedCategoryValues = [String]()
   var trend: Trend!
  var selectedIndex = -1

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

if collectionView == trendCollectionView 


let trendsCell = collectionView.dequeueReusableCell(withReuseIdentifier: 

"trendsCell", for: indexPath) as! TrendsCollectionCell

trendsCell.layer.cornerRadius = 9.0

trendsCell.layer.borderWidth = 0.1

trendsCell.layer.borderColor = UIColor.lightGray.cgColor


 if selectedIndex == indexPath.row 
            trendsCell.isSelected = true
              else 

            trendsCell.isSelected = false




func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 

            if collectionView == trendCollectionView 

     guard selectedIndex != indexPath.row elsereturn
     let indexpath = IndexPath(row:selectedIndex, section: 0)
     trendCollectionView.cellForItem(at: indexpath)?.isSelected = !trendCollectionView.cellForItem(at: indexpath)!.isSelected


        switch selectedSegmentIndex 

        case 0: self.trend = femaleTrends[indexPath.row]
        print("You selected  \(trend.childValue)")
        self.selectedCategoryValues.append(trend.childValue)




        case 1: self.trend = maleTrends[indexPath.row]
            print("You selected  \(trend.childValue)")
            self.selectedCategoryValues.append(trend.childValue)


             default: break

        

集合视图单元格

class TrendsCollectionCell: UICollectionViewCell 


    override var isSelected: Bool
        didSet
            if isSelected 

              setSelectedUI()

            
            else

                setUnSelectedUI()

            

        
    

    func setSelectedUI()

    trendCheckmark.isHidden = false
    trendCheckmark.tintColor = .white

    

    func setUnSelectedUI()
        // reset to deafault, hide checkmark
        trendCheckmark.isHidden = true

    


【问题讨论】:

在 indexPath 也显示你的单元格 【参考方案1】:

您可以将选定的索引存储为某个状态的一部分,然后根据需要存储/使用该状态。你可以通过拥有一些属性selectedIndex 来做到这一点,或者,如果你有更多的属性,你可以拥有一些在didSelectItemAt 中更新的结构viewState。然后,您要么在视图控制器之外有一些状态管理器(推荐),要么在视图控制器之间传递状态(如果你有一个简单的应用程序)。

【讨论】:

尽管每个答案都与您首先回答的几乎相同。非常感谢,终于成功了。【参考方案2】:

维持选定单元格状态所需的三个步骤。这适用于table viewcollection view

1. 将上次选定的索引保持为选定单元格。

2. 在每次选择调用时更新cellindex

3. 对于每个cellforrowindex 方法,检查此selected 单元格是否。

进一步的解释是我之前的回答 https://***.com/questions/59293617/multiple-cells-selected-on-scrolling-reuse-cells-problem/

【讨论】:

【参考方案3】:

我从不建议使用单元格选择变量来检测单元格选择,因为该变量不能完全描述状态,因为 UICollectionView 和 UITableView 的出队和回收机制,所以我建议每次都将所有状态依赖于模型, 所以你有2个选择

    为每个单元格模型对象添加一个 isSelected 属性 将 Single 属性添加到保留所选索引的视图控制器中

导入基础

 class NumberCountDataSource: NSObject , UICollectionViewDataSource 
        let selectionAction: ((Int)->())
        let numbersCount: Int
        var selectedIndex: Int?
        init(cardsCount: Int,selectionAction: @escaping ((Int)->())) 
            self.numbersCount = cardsCount
            self.selectionAction = selectionAction

        
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
            return  numbersCount
        

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NumberCollectionViewCell.identiefier, for: indexPath) as! NumberCollectionViewCell
            cell.configure(number: indexPath.row + 1, isSelected: indexPath.row == selectedIndex)
            return cell
        

    

extension NumberCountDataSource: UICollectionViewDelegate , UICollectionViewDelegateFlowLayout 

        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
            selectedIndex = indexPath.row
            self.selectionAction(indexPath.row)
        

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat 
            return CGFloat.init(0.0)
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat 
            return CGFloat.init(0.0)
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
            return CGSize.init(width: 60, height: 50)
        
    

类 NumberCollectionViewCell: UICollectionViewCell

@IBOutlet weak var numberLable: UILabel!
@IBOutlet weak var backGroundview: AnimatableView!
static let identiefier: String = "NumberCollectionViewCell"
static let nibName: String =  "NumberCollectionViewCell"
override func awakeFromNib() 
    super.awakeFromNib()
    // Initialization code

override var isSelected: Bool 
    didSet 

        setupSelection(iseSelected: isSelected)



private func setupSelection(iseSelected: Bool) 
    backGroundview.backgroundColor = isSelected ?  UIColor("#4d8ec5") : UIColor("#ffffff")
    backGroundview.borderColor = isSelected ?  UIColor.clear : UIColor("#707070")
    numberLable.textColor = isSelected ?  UIColor("#ffffff") : UIColor("#444e53")

func configure(number: Int,isSelected: Bool) 
    numberLable.text = "\(number)"
    setupSelection(iseSelected: isSelected)

【讨论】:

您介意给我举个例子来说明如何保留选定的索引吗?这就是我被困在的地方 在示例中我只想显示数字卡集合 抱歉,我很难理解这个问题。那么我会保存所选字符串的数组和索引的数量吗?从未使用didSelect 保存状态,所以如果我的问题是常识,我深表歉意。 我已经可以显示我想要的类别集合,当我选择/取消选择单元格时,复选标记会按预期隐藏和取消隐藏。当我上传照片时,照片也会发布在我选择的正确类别中。但是,当我去编辑那张照片以从我选择的类别中删除照片时,复选标记 .isHidden = true 应该保存并保留复选标记。

以上是关于关闭视图后如何保持集合视图单元格的状态?的主要内容,如果未能解决你的问题,请参考以下文章

向其子视图(即 UILabel)添加约束时,无法保持集合视图单元格的固定大小

如何更改集合视图锡约束中单元格的位置?

在集合视图单元格中自行调整图像大小

如何快速将一半的集合视图单元格放在 UIView 上方? [关闭]

集合视图更改单元格大小

带有有限单元格的集合视图滚动