Adding a UIInterpolatingMotionEffect in one line of code, now with Swift support!

I really like the new UIInterpolatingMotionEffect class. It can make your UI elements look like they are floating above or below other elements with minimal effort. Except it takes 8 lines of code to create it.

What is UIInterpolatingMotionEffect, you say?

motionEffects

I decided to fix that by creating UIView+NaturalMotion.

The methods add all necessary UIInterpolatingMotionEffects to your view to make it look like it’s floating above or below views without the effect.

To make a view look like it’s floating above other views

Objc: [self.logoImageView addNaturalOnTopEffectWithMaximumRelativeValue:5];
Swift: view.addNaturalOnTopEffect(maximumRelativeValue: 5.0)

And to make a view look like it’s floating behind other views

Objc: [self.backgroundImageView addNaturalBelowEffectWithMaximumRelativeValue:15];
Swift: view.addNaturalBelowEffect(maximumRelativeValue: 5.0)

I tried to record a video of the effect but iOS disables it during AirPlay Mirroring.

Get it here https://gist.github.com/maciekish/ecb670b9398d47bdf196

Protip

If you’re trying to create a background image effect like in the Springboard and having trouble sizing your background view so that you don’t get white borders, you should try the following:

  1. Make your UIImageView cover the entire screen and send it to the back.
  2. Set the content mode to center.
  3. Set clips to bounds to false (default).
  4. Make the actual image file slightly larger than the screen, you’ll have to experiment with the values. About 40 pixels extra on each edge works for my “relative value”. If you need to support multiple screen sizes, just name your images properly with @2x and ~iPad etc.

The result is that the UIImageView will only be the size of the screen, but the image inside will be allowed to flow out as you tilt the device. I found this solution is a lot cleaner than setting negative autolayout contstraints to make the UIView larger than the screen which was my first attempt.

Leave a Reply

Your email address will not be published. Required fields are marked *