[英]Delete UICollectionViewCell with UILongPressGestureRecognizer
I have a UICollectionView
that I populate from my Image Library. 我有一个从图片库填充的
UICollectionView
。
I want to be able to delete a cell from the collection by using a UILongPressGestureRecognizer
on the cell. 我希望能够通过在单元格上使用
UILongPressGestureRecognizer
从集合中删除单元格。 The UILongPressGestureRecognizer
is working. UILongPressGestureRecognizer
正在运行。
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Selected cell = %ld",(long)indexPath.item);
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(activateDeletionMode:)];
longPress.delegate = self;
[collectionView addGestureRecognizer:longPress];
}
- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
if (gr.state == UIGestureRecognizerStateBegan)
{
NSLog(@"delete mode");
}
}
In your case try this 在你的情况下试试这个
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Selected cell = %ld",(long)indexPath.item);
UILongPressGestureRecognizer * longPres
= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(activateDeletionMode:)];
longPres.minimumPressDuration = .5; //seconds
longPres.delegate = self;
[self.collectionView addGestureRecognizer: longPres];
}
- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
if (gr.state == UIGestureRecognizerStateBegan)
{
NSLog(@"delete mode");
}
}
in other case you can try this 在其他情况下,您可以尝试此
//add long press gesture to collectionView //将长按手势添加到collectionView
UILongPressGestureRecognizer *longpress
= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongpressMethod:)];
longpress.minimumPressDuration = .5; //seconds
longpress.delegate = self;
[self.collectionView addGestureRecognizer: longpress];
}
then handle the action 然后处理动作
-(void) handleLongpressMethod:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
return;
}
CGPoint pt = [gestureRecognizer locationInView:self.collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pt];
if (indexPath == nil){
NSLog(@"couldn't find index path");
} else {
// get the cell at indexPath (the one you long pressed)
UICollectionViewCell* cell =
[self.collectionView cellForItemAtIndexPath:indexPath];
// work with the cell
}
delete 删除
[self.youritemarray removeObjectAtIndex:indexPathh];
[collectionView reloadData];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.