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

How to maintain state of collection view cell after dismissal of view?

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

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

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

如何在关闭视图控制器后保持 selected 或 deselected 状态?

   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 else{return}
     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

    }

}

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

维护单元格的 selected 状态需要三个步骤。这适用于 table viewcollection view

1. 维护作为 selected 单元格的最后 selected 索引。

2. 在每次 select 调用时更新 cellindex

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

进一步解释在我之前的回答中

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

  1. 向每个单元格 ModelObject 添加一个 isSelcted 属性
  2. 将 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)
        }
    }

class 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)
}

}