在我的视图控制器上使用 UIMotionEffect

Using UIMotionEffect on my view controller

我试图在用户倾斜屏幕时移动对象,但我不知道为什么我的代码不起作用!我错过了什么 ?这是我的代码:

- (void)createMotionEffect:(UIView*)view {

    NSLog(@"itWorks");

    //motion background
    // Set vertical effect
    UIInterpolatingMotionEffect *verticalMotionEffect =
    [[UIInterpolatingMotionEffect alloc]
     initWithKeyPath:@"center.y"
     type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
    verticalMotionEffect.minimumRelativeValue = @(-50);
    verticalMotionEffect.maximumRelativeValue = @(50);

    // Set horizontal effect
    UIInterpolatingMotionEffect *horizontalMotionEffect =
    [[UIInterpolatingMotionEffect alloc]
     initWithKeyPath:@"center.x"
     type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
    horizontalMotionEffect.minimumRelativeValue = @(-50);
    horizontalMotionEffect.maximumRelativeValue = @(50);

    // Create group to combine both
    UIMotionEffectGroup *group = [UIMotionEffectGroup new];
    group.motionEffects = @[horizontalMotionEffect, verticalMotionEffect];

    // Add both effects to your view
    [view addMotionEffect:group];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createMotionEffect:_trex];

}

我正在 iPad Air 上测试,iOS 8.4.1。它适用于 iPhone 但不适用于我的 iPad!

您不能指望运动效果起作用。用户可以关闭它们(这可能是您遇到的情况:您可能已经在 iPad Air 上关闭了此功能)。或者它可能不会产生这些效果;并非所有硬件都如此。

无论如何,您似乎在滥用此功能。运动效果应仅限于典型的警报和设备主视图中的图标的视差效果。当用户倾斜设备时移动视图的方法是检测设备的倾斜(使用 Core Motion)并移动视图作为响应!不要滥用运动效果作为一种廉价的方式来避免在这里做真正的工作。完成工作。