возникли проблемы с прокруткой изображения с помощью гироскопа

#ios #objective-c #iphone #ipad

#iOS #objective-c #iPhone #iPad

Вопрос:

У меня странная проблема с iPad Air !!!, мой код отлично работает на iPad 3, iPad 4, iPhone 5S , iPod 5-го поколения, но на iPad air мое изображение прокручивается автоматически без поворота пользователем устройства, вот мой код :

  @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 (fabs(gyroData.rotationRate.y) >= 0.1) {
            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);
          }
   }];
 

это своего рода анимация!!! этот код отлично работает на других устройствах! какая — нибудь помощь ?Спасибо

Комментарии:

1. Правильно ли работает ваш iPad-гироскоп в других приложениях? Однажды у меня была похожая проблема, и оказалось, что она была вызвана неисправным оборудованием

2. Ваш iPad работает под управлением iOS 8 beta 1 или 2? У меня были большие проблемы с гироскопом в других приложениях, использующих эти бета-версии

3. @Chrene нет, это iOS 7!

4. Вы пробовали использовать другой iPad? Может быть, это очевидно, но это действительно хороший способ выяснить, есть ли у вас проблемы с оборудованием

5. Не могли бы вы записать данные своего гироскопа, пожалуйста, — ваш код считает, что это > = 0.1 NSLog (@»%f»,gyroData.rotationRate.y);

Ответ №1:

не могли бы вы попробовать следующее: это добавляет обработку ошибок в ваш код, поскольку ошибка может возвращаться из гироскопа, и это может возвращать значение> 0.09; Чаще используйте NSLOG при тестировании, чтобы разобрать ваш код и посмотреть, какие значения возвращаются.

 @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);
}];