如何在 UIImageView 上实现点击并按住?
Posted
技术标签:
【中文标题】如何在 UIImageView 上实现点击并按住?【英文标题】:How to implement a tap and hold on an UIImageView? 【发布时间】:2014-07-15 13:29:30 【问题描述】:当我触摸并按住图像 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
【问题讨论】:
您在哪里向 imageView 添加手势?我只能看到处理程序方法 我的错误......在viewDidLoad中。谢谢。 【参考方案1】:-(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 是否重要? 我不这么认为。检查适当的 userInteractionEnabled,应为 YES (true) 基于类参考: userInteractionEnabled 一个布尔值,确定是否忽略用户事件并将其从事件队列中删除。 @property(nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled 讨论 该属性继承自 UIView 父类。此类将此属性的默认值更改为 NO。 为我工作而无需添加行 lpHandler.delegate = self; 对我不起作用,最好遵循这个解决方案:***.com/a/34548629/4994239【参考方案2】:UIImageViews
默认有userInteractionEnabled = NO
。如果您将手势识别器添加到 UIImageView
的实例中,请确保将其设置回 YES:myImageView.userInteractionEnabled = YES
【讨论】:
以上是关于如何在 UIImageView 上实现点击并按住?的主要内容,如果未能解决你的问题,请参考以下文章
iOS 如何在滚动视图/webview 上实现点击手势以“敲出”文本字段?
在pyqt5中的QWidget上实现dragMoveEvent?