【问题标题】:collectionviews in tableview selection表视图选择中的集合视图
【发布时间】:2021-10-06 20:46:58
【问题描述】:

我将我的 UICollectionView 添加到 UITableViewCell(目标 c),并且数据在 tableview 内的 collectionviews 中正确显示,同一个 collectionview 中的选择按预期工作;我遇到的问题是:

如果用户在 collectionview (a) 中选择一个单元格,则该单元格的标签背景颜色设置为红色

当用户在 collectionview (b) 中选择一个单元格时,该单元格的标签背景色设置为红色,但 collectionview a 中前一个选定单元格的背景色仍然是 红色!

我的问题是如何将 clearColor 设置为上一个选定的单元格?

请帮忙谢谢

nb:collectionview的数据和数量是动态的

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   if(self.selectedIndex == indexPath.item)
                             {
                                                                      cell.label.backgroundColor = [UIColor redColor];
                                 }
                  
                             else
                             {
                                cell.label.backgroundColor=[UIColor clearColor];
                                 
                             }
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
     self.selectedIndex = indexPath.row;

}

【问题讨论】:

    标签: ios objective-c uitableview uicollectionview


    【解决方案1】:

    一旦您在 UI 中记录或标记状态,有时这并不简单。 我建议将状态存储在数据模型中,单元格的外观是基于数据模型的,一旦数据模型发生变化,刷新相应的单元格即可。 这是一个简单的例子:

    在 ViewController.m 中

    在 XXCellDataModel.h 在 XXCollectionViewCell.h 在 XXCollectionViewCell.m

    【讨论】:

    • 感谢您的回复,如果您有示例,我会更清楚,谢谢
    • 非常感谢您的帮助,我会尝试您的解决方案谢谢
    • 你好;使用您的代码时出现此错误 [__NSDictionaryI selected]: unrecognized selector sent to instance
    • 你的数据模型是 NSDictionary 吗?如果你使用 NSDictionary,你应该使用 setter 或 getter by 'setObjectForKey:' , 'objectForKey:'