0

我正在尝试创建一个长按手势,一旦按住 3 秒钟,就会显示第二个视图控制器。但是,如果设备在整个 3 秒内处于某个加速度计方向,我只希望显示第二个视图控制器。也就是说,如果手势没有保持足够长的时间或设备倾斜太多,则手势将被取消,用户必须重试。

// 在 FirstViewController.h 中

#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface FirstViewController : UIViewController

@property (nonatomic, strong) CMMotionManager *motionManager;

@end

// 在 FirstViewController.m 中

#import "FirstViewController"
#import "SecondViewController"

@implementation motionManager;

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.motionManager = [[CMMotionManager alloc]init];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 3.0;
    [self.view addGestureRecognizer:longPress];
}

- (void) handleLongPress: (UILongPressGestureRecognizer *)sender
{
    // Not sure what to do here
}

我之前在最后一种方法中尝试过大量代码,但它看起来很讨厌,而且不正确。相反,我在下面列出了几行我知道单独工作的代码,但我需要帮助才能使它们一起工作。

// 加速度计

if ([self.motionManager isAccelerometerAvailable])
{
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData,NSError *error)
    {
        if (ABS(accelerometerData.acceleration.x) < 0.3 && ABS(accelerometerData.acceleration.y) < 0.30 && ABS(accelerometerData.acceleration.z) > 0.70) // Phone is flat and screen faces up
        { 
            NSLog(@"Correct Orientation!!!");
            [self.motionManager stopAccelerometerUpdates];
        }
        else
        {
            NSLog(@"Incorrect orientation!!!");
            [self.motionManager stopAccelerometerUpdates];
        }];
}

else
{
    NSLog(@"Accelerometer is not available.");
}

// 转到第二个视图控制器

if (sender.state == UIGestureRecognizerStateBegan)
{
    SecondViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    [self presentViewController:svc animated:YES completion:nil];
}

有任何想法吗?或者,除非满足条件,否则取消手势的更通用方法将非常有帮助。

4

3 回答 3

0

我希望代码足够冗长以供您阅读,这很容易解释 - 我坚持使用您的加速度计代码,并使用相同的变量名。

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController () {

    NSOperationQueue    *motionQueue;
    NSTimer             *touchTimer;
    NSTimeInterval      initialTimeStamp;
    BOOL                touchValid;

    float                timerPollInSeconds;
    float                longPressTimeRequired;
}

@property (strong, nonatomic)            NSTimer             *touchTimer;
@property (assign, nonatomic)            NSTimeInterval      initialTimeStamp;
@property (assign, nonatomic)            BOOL                touchValid;
@property (assign, nonatomic)            float               timerPollInSeconds;
@property (assign, nonatomic)            float               longPressTimeRequired;
@property (strong, nonatomic)            CMMotionManager     *motionManager;
@property (strong, nonatomic)            NSOperationQueue    *motionQueue;


@end

@implementation ViewController

@synthesize touchTimer = _touchTimer, initialTimeStamp, touchValid, motionQueue = _motionQueue;
@synthesize timerPollInSeconds, longPressTimeRequired, motionManager = _motionManager;

- (void)viewDidLoad
{
    self.timerPollInSeconds = 0.25f;
    self.longPressTimeRequired = 3.0f;
    self.touchTimer = nil;
    self.touchValid = NO;
    self.initialTimeStamp = NSTimeIntervalSince1970;
    self.motionManager = [[CMMotionManager alloc] init];
    self.motionQueue = [[NSOperationQueue alloc] init];
    [_motionQueue setName:@"MotionQueue"];
    [_motionQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];

    [super viewDidLoad];

    self.view.multipleTouchEnabled = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Operations

-(void) startLongPressMonitorWithTimeStamp:(NSTimeInterval) timeStamp {
    NSLog(@"Starting monitoring - %g", timeStamp);
    if( self.touchTimer ) {
        if( [_touchTimer isValid] ) {
            [_touchTimer invalidate];
        }
    }

    self.touchTimer = [NSTimer timerWithTimeInterval:self.timerPollInSeconds target:self selector:@selector(timerPolled:) userInfo:nil repeats:YES];

    if( [_motionManager isAccelerometerAvailable] ) {
        NSLog(@"Accelerometer Available");
        if( ![_motionManager isAccelerometerActive] ) {
            NSLog(@"Starting Accelerometer");
            [_motionManager startAccelerometerUpdatesToQueue:self.motionQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {

                if (ABS(accelerometerData.acceleration.x) < 0.3 && ABS(accelerometerData.acceleration.y) < 0.30 && ABS(accelerometerData.acceleration.z) > 0.70) // Phone is flat and screen faces up
                {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.touchValid = YES;
                    });
                }
                else
                {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.touchValid = NO;
                        [self stopLongPressMonitoring:YES];
                    });
                };
            }];
        }
        else {
            NSLog(@"Accelerometer already active");
        }
    }
    else {
        NSLog(@"Accelerometer not available");
    }

    self.initialTimeStamp = timeStamp;

    self.touchValid = YES;
    [_touchTimer fire];

    [[NSRunLoop mainRunLoop] addTimer:self.touchTimer forMode:NSRunLoopCommonModes];
}



-(void) stopLongPressMonitoring:(BOOL) touchSuccessful {
    [_motionManager stopAccelerometerUpdates];
    [_touchTimer invalidate];
    self.touchValid = NO;

    if( touchSuccessful ) {
        NSLog(@"Yes");
    }
    else {
         NSLog(@"No");
    }
}

#pragma mark - User Interaction
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    //We're using the current times, interval since the touches timestamp refers to system boot up
    // it is more than feasible to use this boot up time, but for simplicity, I'm just using this
    NSTimeInterval timestamp = [NSDate timeIntervalSinceReferenceDate];
    [self startLongPressMonitorWithTimeStamp:timestamp];
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if( self.touchValid && [NSDate timeIntervalSinceReferenceDate] - self.initialTimeStamp == self.longPressTimeRequired ) {
        [self stopLongPressMonitoring:YES];
    }
    else {
        [self stopLongPressMonitoring:NO];
    }
}



#pragma mark - Timer Call back
-(void) timerPolled:(NSTimer *) timer {
    NSTimeInterval firedTimeStamp = [NSDate timeIntervalSinceReferenceDate];
    NSLog(@"Timer polled - %g", firedTimeStamp);
    if( self.touchValid ) {
        NSLog(@"Time elapsed: %d", (int)(firedTimeStamp - self.initialTimeStamp));

        if( firedTimeStamp - self.initialTimeStamp >= self.longPressTimeRequired ) {
            NSLog(@"Required time has elapsed");
            [self stopLongPressMonitoring:YES];
        }
    }
    else {
        NSLog(@"Touch invalidated");
        [self stopLongPressMonitoring:NO];
    }
}


@end
于 2013-08-01T18:04:58.203 回答
0

您可以通过子类化 UIGestureRecognizer来做您想做的事情,以制作您自己的手势识别器,类似于 UILongPressGestureRecognizer 除了至少 3 秒持续时间的按下之外,它还会侦听加速度计数据。

于 2013-07-31T20:03:35.123 回答
0

我可能会覆盖 onTouchesBegan 和 onTouchesEnded 方法,而不是使用手势识别器。

然后我会在你的视图控制器中创建一个 NSTimer 对象、一个 NSTimeInterval 变量和一个 BOOL;为此,我将它们称为 touchTimer、initialTouchTimeStamp 和 touchValid。

为了复杂起见,假设 viewControllers 视图不是多点触控的。

假设repeatTime = 0.25f;longPressTimeRequired = 3;

计时器选择器将包含您的加速度计方法,如果您的加速度计方法中的数据无效,我会将 touchValid 设置为 false(并使计时器无效),否则我会将其设置为 true 检查加速度计后,我会检查我的 initialTouchTimeStamp var 是 longPressTimeRequired 还是早于几秒[touchTimer fireDate] - repeatTime ,如果是,并且 touchValid 为真,那么我将转到我的第二个控制器。

onTouchesBegan,我会使 touchTimer 无效并创建一个新的,它将每隔 repearTime 秒重复一次,并持续 y 秒。将 touchValid 设置为 NO,并将 initialTouchTimeStamp 设置为 touch.timestamp。

onTouchesEnded,我会使 touchTimer 无效,并检查我的 initialTouchTimeStamp var 是否比 longPressTimeRequired 早或更多秒[touchTimer fireDate] - repeatTime ,如果是,并且 touchValid 为真,那么我将转到我的第二个控制器。

这里有很多共同的元素,它可能不是最优雅的做事方式,但它应该可以工作。希望这可以帮助。

于 2013-07-31T20:08:21.787 回答