如何实现点击并按住UIImageView?

时间:2014-07-15 13:29:30

标签: ios objective-c touch gestures

当我触摸并按住图像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];
}

不确定这是否会产生任何影响,但图像视图是以后以编程方式创建的,而不是在加载时。如果感谢任何帮助,请提前感谢您。

另外,我查看了以下链接:

Long press gesture on UICollectionViewCell

Long press gesture recognizer on UIButton?

Apple Link 1

Apple Link 2

2 个答案:

答案 0 :(得分: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
   }

}

答案 1 :(得分:3)

默认情况下,

UIImageViewsuserInteractionEnabled = NO。如果您要将手势识别器添加到UIImageView的实例,请确保将其设置回YES:myImageView.userInteractionEnabled = YES