我一直试图在用户点击集合视图的单元格时添加一个复选标记,如果再次点击它 - 将其删除。
到目前为止,我已经编写了一个添加复选标记的代码,但我仍然找不到删除它的方法。
我的代码:
- (void)profilePicked:(UIGestureRecognizer*)gesture {
UIView *pickedView = (UIView* )[gesture view];
UIImageView *tick = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ticker"]];
tick.frame = CGRectMake(0, 0, 110, 110);
tick.tag = 105;
tick.contentMode = UIViewContentModeScaleAspectFit;
if(![pickedView.subviews containsObject:tick]) {
[pickedView addSubview:tick];
} else {
for (UIView *subview in pickedView.subviews) {
if (subview.tag == 105) {
[subview removeFromSuperview];
}
} [self.profilesCollection reloadData];
}
}
和:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"profileCell";
InviterCollectionViewCell *cell = (InviterCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
// some stuff happening here
UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 110)];
//cell.profilePicture.frame = CGRectMake(0, 0, 110, 110);
//cell.profilePicture.contentMode = UIViewContentModeScaleAspectFill;
[circle addSubview:imageView];
// Round the edges of the profile picture
circle.layer.cornerRadius = 55;
circle.clipsToBounds = YES;
[cell.contentView addSubview:circle];
cell.ticker.hidden = YES;
//Add Gesture Recognizer for the profile Picture
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(profilePicked:)];
tapped.numberOfTapsRequired = 1;
[circle addGestureRecognizer:tapped];
circle.userInteractionEnabled = YES;
return cell;
}
我尝试在didSelectItemAtIndexPath和didDeselectItemAtIndexPath中实现一些功能,但它没有按预期工作。
非常感谢任何帮助。
答案 0 :(得分:2)
试试这个解决方案:
1 将带有复选标记图像的UIImageView添加到storyboard或nib文件中的单元格,然后为此imageView创建插座并将其设置为隐藏模式
2 在didSelectItemIndexPath方法中添加以下代码:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//check if the the checkmark image is hidden then change it to visible
if(cell.checkMarkImage.hidden)
cell.checkMarkImage.hidden = NO;
else
cell.checkMarkImage.hidden = YES;
[cell setSelected:YES];
}