openfrog
openfrog

Reputation: 40735

How to obtain parallax motion offset similar to iOS 7 home screen with support for iOS 6?

I read here that iOS 7 offers a simple way to get parallax motion offsets. But it also shows you have to apply it to a UIView.

I need it for something different (a drawing algorithm). What would you do to obtain the pure CGPoint parallax motion offset if you would not want to create a hidden view just to obtain the value?

And how could I get this parallax motion offset so it also runs with iOS 6?

Upvotes: 3

Views: 534

Answers (1)

Vishal V. Shekkar
Vishal V. Shekkar

Reputation: 341

This answer is 3 years too late.

But, you could subclass UIMotionEffect and override keyPathsAndRelativeValues(forViewerOffset:) and implement whatever effect you want to apply to the view based on the viewer's viewing position.

The parameter viewerOffset provides an instance of UIOffset which will give you the viewing offset of the viewer. You need to return a dictionary with keyPaths as keys and the corresponding values that you compute based on the viewerOffset as the values for any of the animatable properties of the view.

import UIKit

class CustomMotionEffect: UIMotionEffect {

    override func keyPathsAndRelativeValues(forViewerOffset viewerOffset: UIOffset) -> [String : Any]? {
        var motionEffectDictionary = [String : Any]()

        //Horizontal
        if viewerOffset.horizontal > 0 { //Device tilted right

        } else if viewerOffset.horizontal < 0 { //Device tilted leftß

        } else {//Device horizontally perpendicular

        }

        //Vertical
        if viewerOffset.vertical > 0 { //Device tilted down

        } else if viewerOffset.vertical < 0 { //Device tilted up

        } else { //Device vertically perpendicular

        }
        return motionEffectDictionary
    }

}

Doing this will ensure you have control over how your effect should behave. But, this won't work on iOS6.

Upvotes: 1

Related Questions