- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//NSLog(@"enter category cell");
CategoryViewCell* cell = (CategoryViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
[cell.imgCat setImage:[UIImage imageNamed:[categoryImages objectAtIndex:indexPath.row]]];
[cell.labelCatName setText:[[NSString stringWithFormat:@"%@", [catName objectAtIndex:indexPath.row]] capitalizedString]];
if([categories[[NSString stringWithFormat:@"%d",(int)indexPath.row]] isEqual:@YES]) {
//NSLog(@"set border");
cell.layer.borderColor = [UIColor redColor].CGColor;
cell.layer.borderWidth = 3;
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
CategoryViewCell* cell = (CategoryViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.layer.borderWidth = 3;
cell.layer.borderColor = [UIColor redColor].CGColor;
//NSLog(@"%i", (int)indexPath.item);
categories[[NSString stringWithFormat:@"%i", (int)indexPath.item]] = @YES;
}
-(void) collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
CategoryViewCell* cell = (CategoryViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.layer.borderColor = [UIColor clearColor].CGColor;
categories[[NSString stringWithFormat:@"%i", (int)indexPath.item]] = @NO;
}
问题:上面的代码将向您显示一个collectionView,其中包含默认选中的单元格。但是,这些选定单元格的状态不会被选中。所以我必须点击两次才能取消选择它们,因为第一次点击是为了选择它们,第二次点击是为了取消选择它们。
我已经尝试为单元格设置选定,但它也不起作用。每当用户选择一个单元格时,该单元格都会有一个红色边框,当用户取消选择该单元格时,该单元格将显示clearColor。
我试过了:
cell.selected = YES;
但是这会永久地给collectionView单元格一个红色边框。
并将其添加到cellForItemAtIndexPath方法中仍然不起作用。
[self collectionView:collectionView didSelectItemAtIndexPath:indexPath];
CategoryViewCell.m
-(void) setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected];
//NSLog(@"Pass Select Animated");
if (selected) {
self.flagHighlight = NO;
self.selected = NO;
self.layer.borderColor = [UIColor clearColor].CGColor;
self.layer.borderWidth = 3;
} else {
self.flagHighlight = YES;
self.selected = YES;
self.layer.borderColor = [UIColor redColor].CGColor;
self.layer.borderWidth = 3;
}
}
如何在以编程方式加载视图时预选单元格?或者更好的方法是改变被选中的单元格的状态。
提前谢谢。
发布于 2015-03-17 12:10:02
最终回答了我自己的问题。
所以我使用[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
在cellForItemAtIndexPath中。
很好地服务于这个目的。
https://stackoverflow.com/questions/29093973
复制相似问题