Skip to content

Instantly share code, notes, and snippets.

@Infinity-James
Created November 17, 2018 15:02
Show Gist options
  • Save Infinity-James/cf4fbd319403a9ddfd92b966f91a6125 to your computer and use it in GitHub Desktop.
Save Infinity-James/cf4fbd319403a9ddfd92b966f91a6125 to your computer and use it in GitHub Desktop.
Allows for easily setting a theme on the navigation bar.
//
// NavigationTheme.swift
//
// Created by James Valaitis on 13/04/2018.
//
import UIKit
// MARK: Navigation Theme
/**
Encapsulates the information to theme a navigation controller.
*/
public struct NavigationTheme {
// MARK: Properties
/// The text attributes for the navigation bar.
let titleTextAttributes: [NSAttributedString.Key: Any]
/// The color for the navigation bar.
let barTintColor: UIColor
/// The color for the buttons in the navigation bar.
let tintColor: UIColor
/// The image for the shadow below the navigation bar.
let shadowImage: UIImage
/// Whether or not the bar should be translucent.
let isTranslucent: Bool
/// The background image for the navigation bar.
let backgroundImage: UIImage
}
// MARK: Initialization
public extension NavigationTheme {
init(attributes: [NSAttributedString.Key: Any], barColor: UIColor, tintColor: UIColor, shadowImage: UIImage = UIImage(), translucent: Bool = true, backgroundImage: UIImage = UIImage()) {
self.init(titleTextAttributes: attributes, barTintColor: barColor, tintColor: tintColor, shadowImage: shadowImage, isTranslucent: translucent, backgroundImage: backgroundImage)
}
}
// MARK: Constants
public extension NavigationTheme {
/// A transparent navigation bar with white buttons.
static var transparentWhite: NavigationTheme { return NavigationTheme(attributes: [.font: UIFont(name: .avenirNextRegular, size:14.0)], barColor: .clear, tintColor: .white) }
}
// MARK: UINavigationBar + NavigationTheme
public extension UINavigationBar {
func apply(_ theme: NavigationTheme, withTransition fading: Bool = false, fadingTime time: CFTimeInterval = 0.25) {
barTintColor = theme.barTintColor
titleTextAttributes = theme.titleTextAttributes
tintColor = theme.tintColor
shadowImage = theme.shadowImage
isTranslucent = theme.isTranslucent
if fading {
let transition = CATransition()
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.type = .fade
transition.duration = time
self.layer.add(transition, forKey: nil)
}
setBackgroundImage(theme.backgroundImage, for: UIBarMetrics.default)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment