having issue with scrolling image with gyroscope

前端 未结 1 901
深忆病人
深忆病人 2021-01-17 23:59

I have a strange problem with iPad Air !!! , my code runs fine on iPad 3 , iPad 4 , iPhone 5S , iPod 5th Gen , but on iPad air , my image scrolls automatically without user

相关标签:
1条回答
  • 2021-01-18 00:11

    could you try the following: This adds the error handling to your code, as an error may be returning from the gyroscope, and this may return a value >0.09; Use NSLOG more often when testing to pick apart your code and see what values are returning.

    @property (strong, nonatomic) CMMotionManager *motionManager;
    
    
    self.mainScrollView.frame = CGRectMake(0, 0, self.view.frame.size.width,       self.view.frame.size.height);
    
    self.mainScrollView.bounces = NO;
    
    
    self.mainScrollView.userInteractionEnabled = NO;
    
    //set up the image view
    UIImage *image= [UIImage imageNamed:@"YOUR_IMAGE_NAME"];
    UIImageView *movingImageView = [[UIImageView alloc]initWithImage:image];
    [self.mainScrollView addSubview:movingImageView];
    
    self.mainScrollView.contentSize = CGSizeMake(movingImageView.frame.size.width, self.mainScrollView.frame.size.height);
    
    
    self.mainScrollView.contentOffset = CGPointMake((self.mainScrollView.contentSize.width - self.view.frame.size.width) / 2, 0);
    
    //inital the motionManager and detec the Gyroscrope for every 1/60 second
    //the interval may not need to be that fast
    self.motionManager = [[CMMotionManager alloc] init];
    self.motionManager.gyroUpdateInterval = 1/60;
    
    //this is how fast the image should move when rotate the device, the larger the number, the less the roation required.
    CGFloat motionMovingRate = 4;
    
    //get the max and min offset x value
    int maxXOffset = self.mainScrollView.contentSize.width - self.mainScrollView.frame.size.width;
    int minXOffset = 0;
    
    [self.motionManager startGyroUpdatesToQueue:[NSOperationQueue currentQueue]
                                withHandler:^(CMGyroData *gyroData, NSError *error) {
    // IF NO ERROR ---
    if(!error){
    NSLog(@"No error from Gyroscope %f",gyroData.rotationRate.y);
         if (fabs(gyroData.rotationRate.y) >= 0.1) {
    NSLog(@"Moving image");
            CGFloat targetX = self.mainScrollView.contentOffset.x - gyroData.rotationRate.y * motionMovingRate;
    
             if(targetX > maxXOffset)
                   targetX = maxXOffset;
             else if (targetX < minXOffset)
                   targetX = minXOffset;
    
    
             self.mainScrollView.contentOffset = CGPointMake(targetX, 0);
          }
    }
    // ERROR returned from GYRO
    else NSLog(@"error recieved %@",error);
    }];
    
    0 讨论(0)
提交回复
热议问题