gpt4 book ai didi

ios - UILongPressGestureRecognizer 不会响应触摸和按住

转载 作者:可可西里 更新时间:2023-11-01 03:28:33 25 4
gpt4 key购买 nike

我正在为 iPhone 编写 Objective-C 程序。

我正在尝试实现一个 UILongPressGestureRecognizer,但无法让它按照我想要的方式运行。

想要做的很简单:

响应在屏幕上按住的触摸。

每当触摸移动和触摸开始时,UILongPressGestureRecognizer 都能正常工作,但如果我在同一个地方按住触摸,则什么也不会发生。

为什么?

我如何处理触摸开始、不动并停留在完全相同的位置?

这是我当前的代码。


// Configure the press and hold gesture recognizer 
touchAndHoldRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(touchAndHold:)];
touchAndHoldRecognizer.minimumPressDuration = 0.1;
touchAndHoldRecognizer.allowableMovement = 600;
[self.view addGestureRecognizer:touchAndHoldRecognizer];

最佳答案

您描述的行为是标准行为,您的手势识别器在您不动时不会收到对您的处理程序的进一步调用。 state当您移动时,这些手势的属性属于 UIGestureRecognizerStateChanged 类型,所以如果事情没有改变,你的处理程序将不会被调用是有道理的。

你可以

  • 使用 state 调用您的手势识别器时的 UIGestureRecognizerStateBegan启动重复计时器;
  • 使用 state 调用您的手势识别器时的 UIGestureRecognizerStateCancelled , UIGestureRecognizerStateFailed , 或 UIGestureRecognizerStateEnded然后invalidate并释放计时器;
  • 确保手势识别器方法正在保存您在某些类属性中查找的任何值(例如 locationInView 的值或其他值)

所以,也许是这样的:

@interface ViewController ()

@property (nonatomic) CGPoint location;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

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

- (void)handleTimer:(NSTimer *)timer
{
[self someMethod:self.location];
}

- (void)handleGesture:(UIGestureRecognizer *)gesture
{
self.location = [gesture locationInView:self.view];

if (gesture.state == UIGestureRecognizerStateBegan)
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
}
else if (gesture.state == UIGestureRecognizerStateCancelled ||
gesture.state == UIGestureRecognizerStateFailed ||
gesture.state == UIGestureRecognizerStateEnded)
{
[self.timer invalidate];
self.timer = nil;
}

[self someMethod:self.location];
}

- (void)someMethod:(CGPoint)location
{
// move whatever you wanted to do in the gesture handler here.

NSLog(@"%s", __FUNCTION__);
}

@end

关于ios - UILongPressGestureRecognizer 不会响应触摸和按住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com