Messages-like taller / standard navigation bar during push / pop - ios

iOS 10 Messages app's navigation bar increases/decreases the height when you push/pop a conversation (with a smooth transition).
Typically I make a taller custom navigation bar using sizeThatFits:, but it persists across pushes and pops of view controllers in a navigation controller.
How is it possible to have a taller navigation bar just for some view controllers across navigation sequences like the Messages app?
Thanks!

Very interesting problem. I spent some time to achieve something like this in the Messages app and that is what I've done.
Finally, I use this trick to animate navigationBar height during push/pop and also pop with swipe gesture.
UIView.beginAnimations(nil, context: nil)
self.frame = navFrame
UIView.commitAnimations()
Below you can see my implementation:
extension UINavigationBar {
func applyHeight(_ height: CGFloat, animated: Bool = true) {
var navFrame = self.frame
navFrame.size.height = height
if animated {
UIView.beginAnimations(nil, context: nil)
self.frame = navFrame
UIView.commitAnimations()
} else {
self.frame = navFrame
}
}
}
class ViewControllerA: UIViewController {
override func loadView() {
super.loadView()
title = "A"
view.backgroundColor = .blue
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "NEXT", style: .plain, target: self, action: #selector(self.showController))
navigationController?.navigationBar.isTranslucent = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func showController() {
navigationController?.pushViewController(ViewControllerB(), animated: true)
}
}
class ViewControllerB: UIViewController {
override func loadView() {
super.loadView()
title = "B"
view.backgroundColor = .red
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.applyHeight(100)
super.viewWillAppear(animated)
}
override func willMove(toParentViewController parent: UIViewController?) {
if parent == nil { // here you know that back button was tapped
navigationController?.navigationBar.applyHeight(44)
}
super.willMove(toParentViewController: parent)
}
}
Things to improve
Title jumps to top
Jumping title is visible while you swipe to pop, but personally, I think this is a small problem :)
Hope it helps you, and maybe someone can improve this implementation. Of course, I will still try to figure out how to make this better :)
Here it's a github repository. Please use navigation_bar_height branch.

I think now you can achieve something similar with just this, just set large title to always:

Related

How put UIBarButtonItem on ViewController of NavigationController on Swift4?

I've a three screens for navigate. But in one these, I can't put a UIBarButtoItem. This screen, is for create a register, and I wants create a button to "Save", that simple. When I did, I select the Bar Button Item, the XCode do not leave me drop on the bar. And programatically, also not works.
I tried this: (Not happens)
var btSalvar : UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
btSalvar = UIBarButtonItem(title: "Salver", style: .plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem = btSalvar
// Do any additional setup after loading the view.
}
And in storyboard: (Note: The Button "Item" not keep fixed on the bar)
You have many options to do that, One of them is:
You have to create a super view controller and add navigation button code in it. I have added a back button for a demo:
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
/**
To add the left back button on navigation.
*/
var addLeftBarMenuButtonEnabled: Bool? {
didSet {
if addLeftBarMenuButtonEnabled! {
let leftBarBtn = UIButton()
leftBarBtn.setImage(UIImage(named: "backIcon"), for: .normal)
leftBarBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
leftBarBtn.addTarget(self, action: #selector(actionBackButton), for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBarBtn)
} else {
self.navigationItem.setHidesBackButton(true, animated: true)
}
}
}
///This is action method for back button
#objc func actionBackButton() {
self.view.endEditing(true)
self.navigationController?.popViewController(animated: true)
}
}
Now you need to use the back button in your view controller which super view controller is MainViewController:
class ViewController: MainViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.addLeftBarMenuButtonEnabled = true
}
}
You can add navigation button like that and use where you want. If you want to use it in every view controller then you have to add 'self.addLeftBarMenuButtonEnabled = true' in main view controller like that
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.addLeftBarMenuButtonEnabled = true
}
}

UINavigationBar change colors on push

I'm using 2 different bar tint colors at UINavigationBar in different views. I'n changing color with that method in both views:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.barTintColor = COLOR
}
When I tap on back button color is not changed smoothly (you can see blink on last second).
But everything is okay if just swipe view back instead of tapping on back button.
How to make smooth transition in both situations?
To achieve this kind of animation you should use UIViewControllerTransitionCoordinator as Apple documentation say it is :
An object that adopts the UIViewControllerTransitionCoordinator protocol provides support for animations associated with a view controller transition.(...)
So every UIViewController has own transitionController. To get this you should call in the UIViewControllerClass :
self.transitionCoordinator()
From documentation:
Returns the active transition coordinator object.
So to get the result that you want you should implement animateAlongsideTransition method in viewController transitionCoordinatior. Animation works when you click backButton and swipe to back.
Example :
First Controller :
class ViewControllerA: UIViewController {
override func loadView() {
super.loadView()
title = "A"
view.backgroundColor = .white
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "NEXT", style: .plain, target: self, action: #selector(self.showController))
setColors()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
animate()
}
func showController() {
navigationController?.pushViewController(ViewControllerB(), animated: true)
}
private func animate() {
guard let coordinator = self.transitionCoordinator else {
return
}
coordinator.animate(alongsideTransition: {
[weak self] context in
self?.setColors()
}, completion: nil)
}
private func setColors() {
navigationController?.navigationBar.tintColor = .black
navigationController?.navigationBar.barTintColor = .red
}
}
Second Controller:
class ViewControllerB : UIViewController {
override func loadView() {
super.loadView()
title = "B"
view.backgroundColor = .white
setColors()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
animate()
}
override func willMove(toParentViewController parent: UIViewController?) { // tricky part in iOS 10
navigationController?.navigationBar.barTintColor = .red //previous color
super.willMove(toParentViewController: parent)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.navigationBar.barTintColor = .blue
}
private func animate() {
guard let coordinator = self.transitionCoordinator else {
return
}
coordinator.animate(alongsideTransition: {
[weak self] context in
self?.setColors()
}, completion: nil)
}
private func setColors(){
navigationController?.navigationBar.tintColor = .black
navigationController?.navigationBar.barTintColor = .blue
}
}
UPDATE iOS 10
In the iOS 10 the tricky part is to add the willMoveTo(parentViewController parent: UIViewController?) in the second ViewController. And set the navigationBar tintColor to the color value of previous controller. Also, in viewDidAppear method in second ViewControler set the navigationBar.tintColor to the color from second viewController.
Check out my example project on github
I've coded final solution that looks most comfortable to use (don't need to use a lot of overrides in own view controllers). It works perfectly at iOS 10 and easy adoptable for own purposes.
GitHub
You can check GitHub Gist for full class code and more detailed guide, I won't post full code here because Stackoverflow is not intended for storing a lot of code.
Usage
Download Swift file for GitHub. To make it work just use ColorableNavigationController instead of UINavigationController and adopt needed child view controllers to NavigationBarColorable protocol.
Example:
class ViewControllerA: UIViewController, NavigationBarColorable {
public var navigationBarTintColor: UIColor? { return UIColor.blue }
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Push", style: .plain, target: self, action: #selector(self.showController))
}
func showController() {
navigationController?.pushViewController(ViewControllerB(), animated: true)
}
}
class ViewControllerB: UIViewController, NavigationBarColorable {
public var navigationBarTintColor: UIColor? { return UIColor.red }
}
let navigationController = ColorableNavigationController(rootViewController: ViewControllerA())
This worked for me:
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
navigationController?.navigationBar.barTintColor = previous view controller's navigation bar color
}
I am just wondering. For the same purpose I use UINavigationControllerDelegate. In navigationController(_:willShow:) I start the animation using transitionCoordinator?.animate(alongsideTransition:completion:). It works great when pushing new controllers, however pop doesn't.
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let dst = viewController as! ViewController
guard animated else {
navigationController.navigationBar.barTintColor = dst.navigationBarColor
navigationController.navigationBar.tintColor = dst.tintColor
navigationController.navigationBar.barStyle = dst.barStyle
return
}
navigationController.transitionCoordinator?.animate(alongsideTransition: { context in
navigationController.navigationBar.barTintColor = dst.navigationBarColor
navigationController.navigationBar.tintColor = dst.tintColor
navigationController.navigationBar.barStyle = dst.barStyle
}, completion: { context in
if context.isCancelled {
let source = context.viewController(forKey: UITransitionContextViewControllerKey.from) as! ViewController
navigationController.navigationBar.barTintColor = source.navigationBarColor
navigationController.navigationBar.tintColor = source.tintColor
navigationController.navigationBar.barStyle = source.barStyle
}
})
Do you see any reason why it should work with pushes but not pops?

Removing the view controller from memory after logging out?

I have a collection view of cells that scroll horizontally. Every time I log out, my main view controller gets dismissed to the log in screen. But when I log back in, it seems that my main view controller was never removed from memory. I say this because my collection view cells are in the same position as they were before I logged out.
I tried everything, from viewWillAppear and reloading the data, to trying to bring my log in view controller as my root window. Any suggestions?
(To be clearly demonstrate this, when you log out of Instagram (from the settings view controller), a log-in view is presented modally. When you log back in, you are presented with the Home feed, instead of the settings view controller. I want to reset the hierarchy of data)
class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let feedId = "feedId"
var allUserCategory: AllUserCategory?
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.pagingEnabled = true
collectionView?.backgroundColor = UIColor(r: 250, g: 250, b: 250)
collectionView?.registerClass(AllUserCategory.self, forCellWithReuseIdentifier: feedId)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Log Out", style: .Plain, target: self, action: #selector(handleLogout))
navigationItem.rightBarButtonItem?.tintColor = UIColor.blueColor()
navigationController?.navigationBar.translucent = false
checkIfUserLoggedIn()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.collectionView?.reloadData()
}
func handleLogout() {
print("Logged out")
do {
try FIRAuth.auth()?.signOut()
} catch let logoutError {
print(logoutError)
}
allUserCategory?.users.removeAll()
let loginController = LoginController()
let loginNav = UINavigationController(rootViewController: loginController)
presentViewController(loginNav, animated: true, completion: nil)
}
}
Add NSLog in dealloc
And maybe you have some memory leak in your code(MainViewController).
Use weak reference for IBOutlet and custom delegate

How to change the size of a popover

I'm having trouble changing the size of my popover presentation. Here is what I have so far
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) // func for popover
{
if segue.identifier == "popoverView"
{
let vc = segue.destinationViewController
let controller = vc.popoverPresentationController
if controller != nil
{
controller?.delegate = self
controller?.sourceView = self.view
controller?.sourceRect = CGRect(x:CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds),width: 315,height: 230)
controller?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
}
}
So far all this does is center the popover and remove the arrow, which is good. but it doesn't resize the container. any help would be greatly appreciated. thank you.
when I use preferredContentSize I get the error "Cannot assign to property: 'preferredContentSize' is immutable"
Set the preferred content size on the view controller being presented not the popoverPresentationController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) // func for popover
{
if segue.identifier == "popoverView"
{
let vc = segue.destinationViewController
vc.preferredContentSize = CGSize(width: 200, height: 300)
let controller = vc.popoverPresentationController
controller?.delegate = self
//you could set the following in your storyboard
controller?.sourceView = self.view
controller?.sourceRect = CGRect(x:CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds),width: 315,height: 230)
controller?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
}
I fixed it via storyboard :
Click on your controller
Click on Attribute inspector
ViewController>
Check Use Preferred Explicit size and input values.
Using Auto Layout
It may be worth mentioning that you can use layout constraints instead of setting preferredContentSize to specific values. To do so,
Add this to your view controller:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.preferredContentSize = self.view.systemLayoutSizeFitting(
UIView.layoutFittingCompressedSize
)
}
Ensure that you have constraints from your popover view to the controller's root view. These can be low priority, space >= 0 constraints.
Above answers are correct which states about using the preferredContentSize, but the most important thing is to implement the protocol UIPopoverPresentationControllerDelegate and implement the below method otherwise it will not change the content size as expected.
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
Similar to Xeieshan's answer above, I set this via the storyboard.
Except that "Presentation" also needed to be to "Form Sheet".
I'm not using storyboards. I just present a UINavigationController in the popover:
self.present(popoverNavigationController!, animated: true) {}
The way to resize the popover size when a new view controller is pushed, it is just change the preferredContentSize before pushing it. For example:
let newViewController = NewViewController()
popoverNavigationController!.preferredContentSize = CGSize(width: 348, height: 400)
popoverNavigationController!.pushViewController(newViewController, animated: true)
The problem is when we try to resize the popover when we pop a view controller.
If you use viewWillDisappear of the current view controller to change the preferredContentSize of the popover, the popover will resize but after the view controller is popped. That means that the animation has a delay.
You have to change the preferredContentSize before executing popViewController. That's mean you have to create a custom back button in the navigation bar like it is explained here. This is the implementation updated for Swift 4:
self.navigationItem.hidesBackButton = true
let newBackButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(CurrentViewController.backButtonTapped(sender:)))
self.navigationItem.leftBarButtonItem = newBackButton
And run the next code when the new Back button is pressed:
#objc func backButtonTapped(sender: UIBarButtonItem) {
self.navigationController?.preferredContentSize = CGSize(width: 348, height: 200)
self.navigationController?.popViewController(animated: true)
}
Basically, the preferredContentSize has to be changed before pushing and popping the view controller.

Using Back on Navigation Bar bugs UIBarButtonItem

I have a NavigationBar at the top of a TableView. It looks nice opening/closing the search.
However, if I click on a button in a cell and get directed to another page (with segue); and then use Back button to unwind, it seems like bugged.
()
So it looks like it is pressed and opened but it shouldn't have. It should be looked like the top picture instead (just UIBarButtonItem - search button)
I couldn't figure out the issue creating this problem.
Please note that < Back is created automatically and I didn't write any code to create it. Is there something I am doing wrong?
Update: Added some snippets...
First, created a different class for handling the search
class SearchBarViewController: UIViewController, UISearchBarDelegate {
var searchBar : UISearchBar?
var searchBarWrapper : UIView?
var searchBarButtonItem : UIBarButtonItem?
func constructSearchBar()
{
searchBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "showSearchBar")
self.navigationItem.rightBarButtonItem = searchBarButtonItem
}
func showSearchBar() {
// styling & configuration
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
UIView.animateWithDuration(0.2, animations: {
self.searchBar?.resignFirstResponder()
self.searchBarWrapper?.alpha = 0
}, completion: { (success) -> Void in
self.searchBar = nil
self.searchBarWrapper = nil
self.navigationItem.rightBarButtonItem = self.searchBarButtonItem
})
}
}
And my ViewController:
class ViewController: SearchBarViewController {
override func viewDidLoad() {
super.viewDidLoad()
constructSearchBar()
}
}
Regarding to emrys57's answer, I tried adding viewWillAppear() in my ViewController but I couldn't make it work, as my cancel looks a little different:
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
// Here, I couldn't figure out what to put because
// my searchBarCancelButtonClicked() needs searchBar and
// forces me to use (!) but then it says, it's optional..
}
The answer is...
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
navigationItem.titleView = nil
constructSearchBar()
}
You have not posted code, so it's not entirely clear what's gone wrong. Using UISearchBar, I think you must be handling the buttons separately yourself, as opposed to using UISearchController. I think that you may not be clearing away the search bar when coming back from the second VC. This code clears out the search bar in viewWillAppear:
class ViewController: UIViewController {
var cancelButton: UIBarButtonItem?
var searchButton: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: Selector("searchCancelPressed:"))
searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: Selector("searchPressed:"))
}
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
searchCancelPressed(nil)
}
func searchPressed(sender: AnyObject) {
navigationItem.titleView = UISearchBar()
navigationItem.rightBarButtonItem = cancelButton
}
func searchCancelPressed(sender: AnyObject?) {
navigationItem.titleView = nil
navigationItem.rightBarButtonItem = searchButton
}
}
and that is working nicely for me when I do a push from a button to the second VC and then hit back.
Following the edit to the original question, this code seems to work, although it may not be the most elegant way of constructing the answer:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationItem.titleView = nil
searchBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "showSearchBar")
navigationItem.rightBarButtonItem = searchBarButtonItem
}
The function constructSearchBar no longer needs to be called in viewDidLoad, and can be deleted.

Resources