This is quite a neat effect that you can add to any of your views on your app. Essentially as you move your phone, the accelerometers inside predict the orientation changes of the phone and provide this movement to your view. It is a great trick to help bring attention to prominent views or images in your app. By creating a small extension on the UIView class you will be able to add this effect to any view with one line of code.
Tutorial
First of all, you want to set up a single view application template. Then create a fixed size UIView to contain your main UIImageView. It is important that the clip to bounds attribute for the UIView is set to true and the UIImageView is constrained to be larger than the UIView.
Here is the extension that you will need to add to your project that you can use on any UIView or subclass of UIView.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// Extension | |
extension UIView { | |
func motionEffect(intensity: Int) { | |
// Set vertical effect | |
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) | |
verticalMotionEffect.minimumRelativeValue = –intensity | |
verticalMotionEffect.maximumRelativeValue = intensity | |
// Set horizontal effect | |
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) | |
horizontalMotionEffect.minimumRelativeValue = –intensity | |
horizontalMotionEffect.maximumRelativeValue = intensity | |
// Create group to combine both | |
let group = UIMotionEffectGroup() | |
group.motionEffects = [horizontalMotionEffect, verticalMotionEffect] | |
addMotionEffect(group) | |
} | |
} |
Then we want to connect our UIImageView to an outlet and implement the motion effect in the viewDidLoad method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class InterpolatingMotionEffect: UIViewController { | |
@IBOutlet var exampleView: UIImageView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
// Add motion effect to our example image view | |
// Adjusting the intensity will change the severity of the effect | |
exampleView.motionEffect(intensity: 50) | |
} | |
} |
Adjusting the intensity will change the severity of the effect, reducing the intensity will make the effect less pronounced while increasing the intensity will raise the sensitivity. Be careful of setting the intensity too high, as it could leave your users feeling a bit nauseous!
Here is the full source code for the project: