所以我有一个 collectionView,其中包含一系列趋势,用户可以单击以展示该照片。单击该单元格时,会出现一个复选标记,让用户知道他们已选择该类别,然后他们的 photoId 将输入到数据库中选定的 childValues 中。
如果用户决定要从特定类别中删除照片,则可以选择编辑照片。当我选择编辑个人资料时,应选择的单元格(我在上传照片时选择的单元格)未被选择。
或者比方说,我已经上传了一张照片,但现在我想展示它,当我去编辑照片并点击某个类别时,会出现复选标记,告诉我该类别已被选择。当我按下“保存”时,照片将按预期添加到数据库中所选的 childValue 中,但是当我再次单击“编辑个人资料”时,就会显示 View 。我 10 秒前选择的单元格现在已取消选择。
即使在关闭 View Controller 后,如何保持选定或取消选定状态?
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
}
Collection View 单元格
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
>。然后,您要么在 View Controller 之外拥有一些状态管理器(推荐),要么在 View Controller 之间传递状态(如果您有一个简单的应用程序)。
关于ios - 如何在关闭 View 后保持 Collection View 单元格的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59404144/