Ios CollectionViewCell在滚动时生成随机内容
点击手机后,我的手机背景会变为黄色。当背景为黄色时,它将恢复为默认颜色 一切正常,但如果我开始滚动,一些单元格的背景色将变为黄色,尽管它没有被选中。不幸的是,它具有随机行为 我用Ios CollectionViewCell在滚动时生成随机内容,ios,uikit,uicollectionview,uicollectionviewcell,Ios,Uikit,Uicollectionview,Uicollectionviewcell,点击手机后,我的手机背景会变为黄色。当背景为黄色时,它将恢复为默认颜色 一切正常,但如果我开始滚动,一些单元格的背景色将变为黄色,尽管它没有被选中。不幸的是,它具有随机行为 我用alloc init创建了一个单元格,但现在,它抛出了一个错误,上面写着: cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath: 我使用故事板操纵单元格中的元素,并像这样使用它们 UIColle
alloc init
创建了一个单元格,但现在,它抛出了一个错误,上面写着:
cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath:
我使用故事板操纵单元格中的元素,并像这样使用它们
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"Number Cell"
forIndexPath:indexPath];
UILabel *label = (UILabel *)[cell viewWithTag:100];
label.text = [NSString stringWithFormat:@"%i", indexPath.item + 1];
有什么建议吗
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"Number Cell"
forIndexPath:indexPath];
UILabel *label = (UILabel *)[cell viewWithTag:100];
label.text = [NSString stringWithFormat:@"%i", (int)indexPath.item + 1];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
if ([cell.backgroundColor isEqual:[UIColor yellowColor]]) {
cell.backgroundColor = [UIColor clearColor];
} else {
cell.backgroundColor = [UIColor yellowColor];
}
}
我想
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
每当我轻触手机时就会调用。因此,当颜色清晰时,我会将其更改为黄色,反之亦然。如果您在单元格的
setSelected:
方法中设置黄色背景色,则应自动执行此操作,前提是如果有人调用[cell setSelected:NO]
如果这不起作用,您可以在退出队列后重置单元格的背景色,或者在单元格的
prepareforuse:
方法中重置单元格的背景色 重复使用一个单元会导致非常不可预测的行为。我对一个单元格进行了子分类,使用了背景色清晰的prepareforeuse
,效果是它完全清除了所有单元格。因此,我将它与if(self.selected==YES)
一起使用,但没有结果。我想要一件非常简单的事情——选择和取消选择背景可视化的单元格。@vaberer,你能举一个最简单的例子说明你所做的导致问题的事情吗?@vaberer,正如我在回答的第一部分所说,如果参数为“是”,则最简单的方法可能是在cell类中覆盖setSelected:
,将其设置为黄色,如果参数为“否”,则将其设置为清晰。我不明白为什么要先测试单元格的背景,因为如果用户点击已选择的单元格,它将调用取消选择方法。集合视图将在prepareforeuse中为您调用setSelected:
,因此您只需覆盖setSelected:
,就可以删除didSelectCell…
。完美!我刚刚添加了self.collectionView.allowsMultipleSelection=YES选择和取消选择多个单元格,一切正常。