Created
February 16, 2015 00:47
-
-
Save robnadin/d428fd4b9aa868d0325d to your computer and use it in GitHub Desktop.
Animated navigation bar tint color on push and interactive pop
This file contains hidden or 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
// | |
// DetailViewController.swift | |
// TransitionCoordinator | |
// | |
// Created by Rob Nadin on 15/02/2015. | |
// Copyright (c) 2015 Rob Nadin. All rights reserved. | |
// | |
import UIKit | |
class DetailViewController: UIViewController { | |
private var navigationBar: UINavigationBar! | |
private var barTintColor: UIColor! | |
private var popGesture: UIGestureRecognizer! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
} | |
override func viewWillAppear(animated: Bool) { | |
super.viewWillAppear(animated) | |
self.transitionCoordinator()?.animateAlongsideTransition({ (context) -> Void in | |
self.navigationController?.navigationBar.barTintColor = UIColor.greenColor() | |
}, completion: nil) | |
} | |
override func viewDidAppear(animated: Bool) { | |
super.viewDidAppear(animated) | |
navigationBar = navigationController?.navigationBar | |
barTintColor = navigationBar.barTintColor | |
popGesture = self.navigationController?.interactivePopGestureRecognizer | |
popGesture.addTarget(self, action: "handlePopRecognizer:") | |
} | |
deinit { | |
popGesture.removeTarget(self, action: "handlePopRecognizer:") | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
@objc private func handlePopRecognizer(recognizer: UIScreenEdgePanGestureRecognizer) { | |
var progress = min(1, max(0, recognizer.translationInView(view).x / view.bounds.width)) | |
if recognizer.state == .Changed { | |
navigationBar.barTintColor = colorForProgress(progress) | |
} | |
} | |
private func colorForProgress(progress: CGFloat) -> UIColor? { | |
let (red, green, blue) = redGreenBlueForColor(barTintColor) | |
let (finalRed, finalGreen, finalBlue) = redGreenBlueForColor(UIColor.blueColor()) | |
let newRed = (1 - progress) * red + progress * finalRed | |
let newGreen = (1 - progress) * green + progress * finalGreen | |
let newBlue = (1 - progress) * blue + progress * finalBlue | |
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0) | |
} | |
private func redGreenBlueForColor(color: UIColor) -> (CGFloat, CGFloat, CGFloat) { | |
var red: CGFloat = 0, green: CGFloat = 0 , blue: CGFloat = 0 | |
color.getRed(&red, green: &green, blue: &blue, alpha: nil) | |
return (red, green, blue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment