iOS 7 parallax effect in my view controller

前端 未结 9 2065
终归单人心
终归单人心 2020-11-30 16:27

I\'m developing an app for iOS 7 in Objective-C. I\'ve got a screen in my app with a few buttons and a pretty background image. (It\'s a simple xib with UIButtons

9条回答
  •  鱼传尺愫
    2020-11-30 16:35

    With iOS 7, Apple introduced UIMotionEffect to add Motion effects that are related to the orientation of the user’s device. For example, to emulate the parallax effect on the home screen, you can use the subclass UIInterpolatingMotionEffect, as explained here, just with a few lines of code.

    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 (Thanks to @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)
    

    Also, you can find a bunch of libraries to do this easier or to add this functionality to older iOS versions:

    • NGAParallaxMotion (requires iOS 7).
    • DVParallaxView (requires iOS 5.0 or higher and ARC).
    • MKParallaxView (tested with iOS 6.0, requires ARC).
    • UIView-MWParallax (tested with iOS 6.1, requires ARC).

提交回复
热议问题