拖动时显示UIImageView对象(使用UILongPressGestureRecognizer)

时间:2014-02-16 22:15:54

标签: objective-c drag-and-drop uiimageview long-press

所以我尝试使用ALAssets Framework获取图像缩略图来实现拖放。

我能够让长按手势正常工作(它肯定会根据一些NSLog测试移动一些东西但是不能为我的生活弄清楚如何实际显示缩略图并在主视图中拖动它。请注意,_dNewImageViewIBOutlet作为视图控制器的属性添加的。我正在尝试使用bringSubviewToFront将视图放在前面:但是它没有按预期工作。任何帮助将不胜感激!

以下是处理长按手势的功能:

-(void)longGestureRecognized:(UILongPressGestureRecognizer *)gestureRecognizer{
    gestureRecognizer.delaysTouchesBegan = YES;
    CGPoint newPoint = [gestureRecognizer locationInView:self.collectionView];

    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            dIndexPath = [self.collectionView indexPathForItemAtPoint:newPoint];
            if (dIndexPath == nil){
                NSLog(@"Couldn't find index path");
            }
            dCell = (SKPhotoCell *)[self.collectionView cellForItemAtIndexPath:dIndexPath];
            dImage = [UIImage imageWithCGImage:[dCell.asset thumbnail]];
            _dNewImageView = [[UIImageView alloc] initWithImage:dImage];
            [_dNewImageView setUserInteractionEnabled:YES];
            [[self view] bringSubviewToFront:_dNewImageView];
            break;

        case UIGestureRecognizerStateChanged:
            [_dNewImageView setCenter:newPoint];
            break;

        case UIGestureRecognizerStateEnded:
            break;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要添加两件事:

[self.view insertSubview:_dNewImageView aboveSubview:self.collectionView];无论您在哪里分配和初始化_dNewImageView

[gestureRecognizer setTranslation:CGPointZero inView:gestureRecognizer.view];在你的手势识别方法中。

如果您重复使用_dNewImageView代码建议,则每次调用方法时都不应分配和初始化它。使用[_dNewImageView setImage:dImage];

此外,当您检查indexPath是否存在时,请确保以某种方式实现该方法返回或绕过图像内容。

例如:

- (void) someOtherMethod {
    _dNewImageView = [[UIImageView alloc] init];
    _dNewImageView.frame = CGRectSomething;
    _dNewImageView.userInteractionEnabled = YES;
    [self.view insertSubview:_dNewImageView aboveSubview:self.collectionView];
}

- (void) longGestureRecognized:(UILongPressGestureRecognizer *)gestureRecognizer {
    ...
        case UIGestureRecognizerStateBegan:
            ...
            if (dIndexPath == nil) {
                NSLog(...);
                return; /*or*/ goto noIndexPath;
            }
            ...
        break;

    //if used 'goto'
    noIndexPath:
        [gestureRecognizer setTranslation:CGPointZero inView:gestureRecognizer.view];

    ...
}