|
// Add to View Controller |
|
|
|
override func viewWillAppear(_ animated: Bool) { |
|
super.viewWillAppear(animated) |
|
customNavBar?.makeTransparent = true |
|
|
|
// Match the style based scroll view position on the page everytime view appears |
|
styleNavBarBasedOnScrollViewPosition(tableView) |
|
} |
|
|
|
override func viewWillDisappear(_ animated: Bool) { |
|
super.viewWillDisappear(animated) |
|
customNavBar?.makeTransparent = false |
|
customNavBar?.layoutSubviews() |
|
} |
|
|
|
override func scrollViewDidScroll(_ scrollView: UIScrollView) { |
|
styleNavBarBasedOnScrollViewPosition(scrollView) |
|
} |
|
|
|
func styleNavBarBasedOnScrollViewPosition(_ scrollView: UIScrollView) { |
|
guard let customNavBar = customNavBar else { return } |
|
let currentY = scrollView.contentOffset.y |
|
let offset: CGFloat = -64.0 |
|
if currentY > offset && currentY < 0 { |
|
let alpha = 1 - (abs(currentY) / abs(offset)) |
|
customNavBar.backgroundView?.backgroundColor = UIColor.white.withAlphaComponent(alpha) |
|
customTitleView.changeAlpha(alpha) |
|
} else if currentY > 0 { |
|
customNavBar.backgroundView?.backgroundColor = UIColor.white |
|
customTitleView.changeAlpha(1) |
|
} else if currentY <= offset { |
|
customNavBar.backgroundView?.backgroundColor = UIColor.clear |
|
customTitleView.changeAlpha(0) |
|
} |
|
customNavBar.layoutSubviews() |
|
} |
|
|
|
// Custom Nav Bar |
|
class CustomNavigationBar: UINavigationBar { |
|
|
|
var makeTransparent = false |
|
var backgroundView: UIView? |
|
|
|
override func layoutSubviews() { |
|
super.layoutSubviews() |
|
restyleBar() |
|
|
|
guard let backgroundView = backgroundView else { return } |
|
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height |
|
backgroundView.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y - statusBarHeight, width: bounds.width, height: bounds.height + statusBarHeight) |
|
sendSubview(toBack: backgroundView) |
|
} |
|
|
|
override init(frame: CGRect) { |
|
super.init(frame: frame) |
|
|
|
hideSeparatorLine() |
|
|
|
barTintColor = UIColor.white |
|
if let font = UIFont(name: "MuseoSans-700", size: 20.0) { |
|
titleTextAttributes = [ |
|
NSFontAttributeName: font, |
|
NSForegroundColorAttributeName: Style.🎀.textBlack90, |
|
] |
|
} else { |
|
titleTextAttributes = [NSForegroundColorAttributeName: Style.🎀.textBlack90] |
|
} |
|
|
|
backgroundView = UIView() |
|
guard let backgroundView = backgroundView else { return } |
|
addSubview(backgroundView) |
|
backgroundView.backgroundColor = UIColor.clear |
|
|
|
// Always set to true and use the backgroundView to control the color / transparency |
|
isTranslucent = true |
|
} |
|
|
|
required init?(coder aDecoder: NSCoder) { |
|
fatalError("init(coder:) has not been implemented") |
|
} |
|
|
|
func restyleBar() { |
|
if !makeTransparent { |
|
backgroundView?.backgroundColor = UIColor.white |
|
} |
|
} |
|
|
|
} |
Thanks for sharing. customTitleView is UIView or UINavigationBar?