如何在UIImageView上实现轻敲和长按操作?

6

我正在尝试在触摸并按住图像2秒钟后调用警报框。以下是我目前所拥有的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILongPressGestureRecognizer *tapAndHoldGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAndHoldGesture:)];
    tapAndHoldGesture.minimumPressDuration = 0.1;
    tapAndHoldGesture.allowableMovement = 600;
    [self.view addGestureRecognizer:tapAndHoldGesture]; 
}

- (void) handleTapAndHoldGesture:(UILongPressGestureRecognizer *)gestureRecognizer{
    if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Gesture:" message:@"hold it" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

不确定这会影响什么,但是Image View是在程序运行后通过编程创建的,而不是在加载时。感谢您的帮助,我们非常感激。

此外,我已经查看了以下链接:

在UICollectionViewCell上进行长按手势

在UIButton上使用长按手势识别器?

苹果链接1

苹果链接2


你在哪里给imageView添加手势?我只能看到处理方法。 - Anil Varghese
我的错误...在viewDidLoad中。谢谢。 - 0--
2个回答

8
-(void)viewDidLoad
{
    [super viewDidLoad];
    [self setupGesture];
}

-(void) setupGesture
{
    UILongPressGestureRecognizer *lpHandler = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleHoldGesture:)];
    lpHandler.minimumPressDuration = 1; //seconds
    lpHandler.delegate = self;
    //myUIImageViewInstance - replace for your instance/variable name
    [**myUIImageViewInstance** addGestureRecognizer:lpHandler];
}

- (void) handleHoldGesture:(UILongPressGestureRecognizer *)gesture
{
   if(UIGestureRecognizerStateBegan == gesture.state)
   {
        // Called on start of gesture, do work here
   }

   if(UIGestureRecognizerStateChanged == gesture.state)
   {
        // Do repeated work here (repeats continuously) while finger is down
   }

   if(UIGestureRecognizerStateEnded == gesture.state)
   {
        // Do end work here when finger is lifted
   }

}

对我来说仍然不起作用...我的图像是22x22有关系吗? - 0--
我不这么认为。请检查属性userInteractionEnabled,应该是YES(true)。根据类参考:userInteractionEnabled 一个布尔值,确定是否忽略用户事件并从事件队列中删除。@property(nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled 讨论 此属性继承自UIView父类。此类将此属性的默认值更改为NO。 - gabriel
在没有添加 lpHandler.delegate = self; 这行代码的情况下,对我起作用了。 - LuAndre
对我不起作用,最好遵循这个解决方案:https://dev59.com/HlsW5IYBdhLWcg3w0aDL#34548629 - Moosa Baloch

4

UIImageView默认情况下具有userInteractionEnabled = NO。如果您要将手势识别器添加到UIImageView实例中,请确保将其设置回YESmyImageView.userInteractionEnabled = YES


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接