- (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 Cell提供一个红色边框。
并在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;
}
}
以编程方式加载视图时,如何预先选择单元格? 或者甚至更好地改变所选单元的状态。
提前致谢。
答案 0 :(得分:0)
结束回答我自己的问题。
所以我使用[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
in cellForItemAtIndexPath。
很好地服务于目的。