Skip to content

Instantly share code, notes, and snippets.

@bigMOTOR
Created August 12, 2018 10:59
Show Gist options
  • Save bigMOTOR/e7117a39da32be060ffae6924dea5748 to your computer and use it in GitHub Desktop.
Save bigMOTOR/e7117a39da32be060ffae6924dea5748 to your computer and use it in GitHub Desktop.
//
// Parallax.swift
//
// Created by Nikolay Fiantsev on 21/02/2018.
// Copyright © 2018 Nikolay Fiantsev. All rights reserved.
//
import UIKit
enum ParallaxMagnitude: Float {
case background = 10.0
case foregroundSmall = -10.0
case foregroundMiddle = -20.0
case foregroundMax = -40.0
}
protocol Parallax {
var foregroundViews: [UIView] { get }
var backgroundView: UIView { get }
func addParallax()
}
extension Parallax {
func addParallax() {
_addParallaxMotionEffect(toView: backgroundView, magnitude: .background)
_addParallaxMotionEffect(toViews: foregroundViews, magnitude: .foregroundMiddle)
}
private func _addParallaxMotionEffect(toViews views: [UIView], magnitude: ParallaxMagnitude) {
views.forEach {
_addParallaxMotionEffect(toView: $0, magnitude: magnitude)
}
}
private func _addParallaxMotionEffect(toView view: UIView, magnitude: ParallaxMagnitude) {
let xMotion = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
xMotion.minimumRelativeValue = -magnitude.rawValue
xMotion.maximumRelativeValue = magnitude.rawValue
let yMotion = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
yMotion.minimumRelativeValue = -magnitude.rawValue
yMotion.maximumRelativeValue = magnitude.rawValue
let group = UIMotionEffectGroup()
group.motionEffects = [xMotion, yMotion]
view.addMotionEffect(group)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment