我正在使用Objective-C开发适用于iOS 7的应用程序。我的应用程序中有一个带有几个按钮和漂亮背景图像的屏幕。 (这是一个简单的xib,在UIButtons的顶部带有UIImageView。)

我在想,如果这些按钮具有iOS 7主屏幕具有的视差效果,那就太酷了,因此,如果倾斜手机,您会看到背景。

如何在自己的应用中实现这种效果?

最佳答案

在iOS 7中,Apple引入了 UIMotionEffect 来添加与用户设备的方向相关的Motion效果。例如,要在主屏幕上模拟视差效果,只需使用几行代码,就可以使用子类 UIInterpolatingMotionEffect (如here所述)。
Objective-C :

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

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

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

// Add both effects to your view
[myBackgroundView addMotionEffect:group];
Swift (感谢@Lucas):
// Set vertical effect
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y",
type: .TiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = -10
verticalMotionEffect.maximumRelativeValue = 10

// Set horizontal effect
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x",
    type: .TiltAlongHorizontalAxis)
horizontalMotionEffect.minimumRelativeValue = -10
horizontalMotionEffect.maximumRelativeValue = 10

// Create group to combine both
let group = UIMotionEffectGroup()
group.motionEffects = [horizontalMotionEffect, verticalMotionEffect]

// Add both effects to your view
myBackgroundView.addMotionEffect(group)
此外,您可以找到一堆库来简化此操作或将此功能添加到较旧的iOS版本:
  • NGAParallaxMotion(需要 iOS 7 )。
  • DVParallaxView(需要 iOS 5.0 或更高版本,以及 ARC )。
  • MKParallaxView(已通过 iOS 6.0 测试,需要 ARC )。
  • UIView-MWParallax(已通过 iOS 6.1 测试,需要 ARC )。
  • 09-10 01:29
    查看更多