backBarbuttonitem does nothing? - ios

I have set the navigation programmatically
in a view controller I set a backbutton and only change the title as per documentation.
however clicking on the back button in the child controller does nothing.
what did I miss?
> in a viewController
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
self.navigationController?.pushViewController(secondViewController, animated: true)

You have to add a target and action to the button,
let backItem = UIBarButtonItem()
backItem.title = ""
backItem.target = self
backItem.action = #selector(back)
navigationItem.backBarButtonItem = backItem
self.navigationController?.pushViewController(secondViewController, animated: true)
and then implement the back() function.
func back() {
// If your view controller was presented by a navigation controller
self.navigationController?.popViewControllerAnimated(true)
// If your view controller was presented modally
self.presentingViewController?.dismiss(animated: true, completion: nil)
}

Related

Navigation Bar, not displaying on second ViewController

I have created a navigation controller. I added a plus button to the top right of the navigation controller which opens up a new view controller. However, I want the navigation bar to show up on the new screen as well. But it's not showing. What am I doing wrong, or what am I missing? Here is my code:
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var toDoListTextView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Setting the Title for the nav bar
title = "To Do List"
configureNavigationItems()
}
private func configureNavigationItems(){
/* Adding a button on the top right of the screen
* in the navigation bar/controller.
*/
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .add,
target: self,
action: #selector(didTapPlus)
)
}
#objc func didTapPlus(){
let vc = storyboard?.instantiateViewController(identifier: "makeTask") as! makeTaskViewController
vc.modalPresentationStyle = .fullScreen
vc.title = "Create a Task"
vc.view.backgroundColor = .black
vc.navigationItem.leftBarButtonItem = UIBarButtonItem(
title: "Back",
style: .done,
target: self,
action: nil)
present(vc, animated: true)
}
}
Storyboard
Click Here To See Picture
Demo of App
enter image description here
Each modally-presented view controller gets a brand-new view hierarchy. This means that if you want your MakeTaskViewController to have a navigation bar, you'll need to manually add a navigation controller.
class ViewController: UIViewController {
// ... your code ...
#objc func didTapPlus() {
let vc = storyboard?.instantiateViewController(identifier: "makeTask") as! MakeTaskViewController
vc.modalPresentationStyle = .fullScreen
vc.title = "Create a Task"
vc.view.backgroundColor = .black
vc.navigationItem.leftBarButtonItem = UIBarButtonItem(
title: "Back",
style: .done,
target: vc, /// make sure to set `target` as the new view controller
action: #selector(vc.dismissMe))
/// wrap the new view controller in a navigation controller (this adds the top bar)
let navigationController = UINavigationController(rootViewController: vc)
/// so you can actually see the `Create a Task` text,
navigationController.navigationBar.barStyle = .black
present(navigationController, animated: true)
}
}
/// side note: `MakeTaskViewController` and other classes should be Capitalized
class MakeTaskViewController: UIViewController {
#objc func dismissMe() {
self.dismiss(animated: true)
}
}
Result:
Try this!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var toDoListTextView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Setting the Title for the nav bar
title = "To Do List"
configureNavigationItems()
}
private func configureNavigationItems(){
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .add,
target: self,
action: #selector(didTapPlus)
)
}
#objc func didTapPlus(){
let vc = storyboard?.instantiateViewController(identifier: "makeTask") as! makeTaskViewController
vc.modalPresentationStyle = .fullScreen
vc.title = "Create a Task"
vc.view.backgroundColor = .black
vc.navigationItem.leftBarButtonItem = UIBarButtonItem(
title: "Back",
style: .done,
target: self,
action: nil)
navigationController?.pushViewController(vc, animated: true)
//present(vc, animated: true)
}
}
😊

(Swift) Navigation bar is hidden in viewController

I want to present SecondVC from FirstVC and make SecondVC have a rightBarButtonItem called Close which calls an #objc function which dismisses SecondVC.
Also, I want to change secondVC's title from firstVC:
This is how I present SecondVC from the FirstVC:
let secondVC = AdviceDetailsViewController()
secondVC.modalPresentationStyle = .fullScreen
secondVC.title = "Example" //Value of type 'UINavigationController' has no member 'myTitle'
self.present(secondVC, animated: true)
Code for navigationBar in secondVC:
public var myTitle: String = ""
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
self.title = myTitle
self.navigationController?.navigationBar.barTintColor = UIColor.orange
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(closeDetails))
}
#objc func closeDetails() {
self.dismiss(animated: true, completion: nil)
}
No Navigation bar is visible in secondVC, the only visible thing is gray background color.
What should I change? I am doing everything programmatically in this app.
Use this method to show second VC
let nc = UINavigationController(rootViewController: AdviceDetailsViewController())
nc.modalPresentationStyle = . fullScreen
self.present(nc, animated: true)
Regarding your Title issue,
Value of type 'UINavigationController' has no member 'myTitle' Yes its true, because we define myTitle variable on SecondVC,So we assign myTitle like this
let vc = SecondViewController()
vc.myTitle = "My Title"
let nc = UINavigationController(rootViewController: vc)
nc.modalPresentationStyle = . fullScreen
self.present(nc, animated: true)

UIBARBUTTON back action

let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: Selector(("HomeTabController")))
self.navigationItem.leftBarButtonItem = backButton
The above code is the creation of button in navigationController but I can create a button cannot write a specific view controller to open.
I have tried with popViewController and popToRootViewController action, need a specific code for opening a particular viewController in swift, with the help of the particular viewController storyboard id and viewcontrollername.
You need to add func name in #selctor() (Swift 4 version)
let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(goToViewController(_:)))
self.navigationItem.leftBarButtonItem = backButton
You need to create a func.
#objc func goToViewController(_ sender: UIBarButtonItem) {
//write code here to open a view controller
let storyboard = "Main"
let viewControllerIdentifier = "HomeVC"
let viewController = UIStoryboard(name: storyboard, bundle: nil).instantiateViewController(withIdentifier: viewControllerIdentifier) as! HomeVC
//push/present "viewController"
}
in this code just replace ChatVC name to your viewcontroller name
#objc func goToViewController(_ sender: UIBarButtonItem) {
for controller in self.navigationController!.viewControllers as Array {
if controller.isKind(of: ChatVC.self) {
self.navigationController!.popToViewController(controller, animated: true)
break
} else {
self.navigationController?.popViewController(animated: true)
}
}
}

UIBarButtonItem depending on presentation. Swift3

I am facing a problem, because there are two ways how do I display my ViewController.
First way is performSegue(withIdentifier: "segue", sender: self)
It works fine because then I have this back button in my navigationItem:
Then I use this code to present the same ViewController (from another viewController than in the first case):
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let navVC = storyboard.instantiateViewController(withIdentifier: "navViewController") as! UINavigationController
let vc = navVC.topViewController as! ViewController
self.present(navVC, animated: true, completion: nil)
but then I do not have any back button in my ViewController.
My question is: How can I keep my backButton (exactly how it is) when I use this function: performSegue(withIdentifier: "segue", sender: self) , but add button (can look different) when I use this function: self.present(navVC, animated: true, completion: nil)
Note: In my case 1 my segue is connected right to ViewController , but in case 2 I present UINavigationController and ViewController is embed in in this UINavigationController.
Edit: I tried this code, but it always prints: "1.........":
if self.presentingViewController != nil {
print("1..........")
} else if self.navigationController?.presentingViewController?.presentedViewController == self.navigationController {
return print("2.........")
} else if self.tabBarController?.presentingViewController is UITabBarController {
return print("3........")
}
And also this code prints:"Else.............." :
let isPresentingInAddMealMode = presentedViewController is UINavigationController
if isPresentingInAddMealMode {
print("FirstOption......................")
} else {
print("Else......................")
}
If you need more info just let me know.
Thank you very much.
you need to check presentedViewController and add back button as below .
if ([self presentedViewController]) {
// add your back button item here
}
Try this:
let viewController = storyboard?.instantiateViewController(withIdentifier: "Login") as! LoginView
let customNavigation = UINavigationController(rootViewController: viewController)
customNavigation.navigationBar.tintColor = UIColor.black
self.present(customNavigation, animated: true, completion: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Login"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(self.backButton))
}
func backButton() {
self.dismiss(animated: true, completion: nil)
}
Try to set Image in UIBarButtonItem
I have solved it!! I put restorationIdentifier to my root navigationController and then I just check if that is navigationController with my restorationIdentifier like this:
if self.navigationController?.restorationIdentifier == "navViewController"{
let leftItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(goBack))
self.navigationItem.leftBarButtonItem = leftItem //Adds item if id is navViewController
}else{
self.navigationItem.leftBarButtonItem = nil //removes it and keeps "<Back"
}

How to set back button text in Swift

How do you remove the back button text.
Current back button:
< Back
Desired back button:
< AnythingElse
None of these have worked:
self.navigationItem.backBarButtonItem?.title = "Back"
self.backItem?.title = ""
self.navigationController?.navigationBar.backItem?.title = ""
self.navigationItem.backBarButtonItem?.title = ""
self.navigationController?.navigationItem.backBarButtonItem?.title="Back"
self.navigationController?.navigationBar.backItem?.title = ""
self.navigationController?.navigationItem.backBarButtonItem?.title
The back button belongs to the previous view controller, not the one currently presented on screen.
To modify the back button you should update it before pushing, on the view controller that initiated the segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let backItem = UIBarButtonItem()
backItem.title = "Something Else"
navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed
}
Swift 3, 4 & 5:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let backItem = UIBarButtonItem()
backItem.title = "Something Else"
navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed
}
OR
// in your viewDidLoad or viewWillAppear
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "Something Else", style: .plain, target: nil, action: nil)
You can do it from interface builder as follows:
click on the navigation item of previous view controller
from the attributes inspector set the back button text to whatever you want. Thats it!!
You can put this 3 line of code in the ViewController you want to change the back button title.
In your override func viewDidLoad() {}.
let backButton = UIBarButtonItem()
backButton.title = "My Back Button Title"
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
Back-button text is taken from parent view-controller's navigation item title. So whatever you set on previous view-controller's navigation item title, will be shown on current view controller's back button text.
You can just put "" as navigation item title in parent view-controller's viewWillAppear method.
self.navigationItem.title = ""
Another way is to put
self.navigationController?.navigationBar.topItem?.title = ""
in current view controller's viewWillAppear method. This one will cause some other problem if navigation stack is too nested.
If you are using xib file for view controller then do this in your view controller class.
class AboutUsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
setUpNavBar()
}
func setUpNavBar(){
//For title in navigation bar
self.navigationController?.view.backgroundColor = UIColor.white
self.navigationController?.view.tintColor = UIColor.orange
self.navigationItem.title = "About Us"
//For back button in navigation bar
let backButton = UIBarButtonItem()
backButton.title = "Back"
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}
}
The result will be:
I do not know where you have used your methods that you put on your question but I could get the desired result if I use, on my ViewController class (in which I want to change the back button), on viewDidLoad() function, the following line:
self.navigationController?.navigationBar.backItem?.title = "Anything Else"
The result will be:
Before
After
The back button belongs to the previous view controller, not the one currently presented on screen.
To modify the back button you should update it before pushing, add viewdidload :
Swift 4:
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
You can just modify the NavigationItem in the storyboard
In the Back Button add a space and press Enter.
Note: Do this in the previous VC.
This should work:
override func viewDidLoad() {
super.viewDidLoad()
var button = UIBarButtonItem(title: "YourTitle", style: UIBarButtonItemStyle.Bordered, target: self, action: "goBack")
self.navigationItem.backBarButtonItem = button
}
func goBack()
{
self.navigationController?.popViewControllerAnimated(true)
}
Although it is not recommended since this actually replaces the backButton and it also removed the back arrow and the swipe gesture.
Swift 4.2
If you want to change the navigation bar back button item text, put this in viewDidLoad of the controller BEFORE the one where the back button shows, NOT on the view controller where the back button is visible.
let backButton = UIBarButtonItem()
backButton.title = "New Back Button Text"
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
If you want to change the current navigation bar title text use the code below (note that this becomes the default back text for the NEXT view pushed onto the navigation controller, but this default back text can be overridden by the code above)
self.title = "Navigation Bar Title"
Swift 4 - Configure the back button before pushing any view controllers
// if you want to remove the text
navigationItem.backBarButtonItem = UIBarButtonItem()
// if you want to modify the text to "back"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: nil, action: nil)
There are two ways.
1.In the previousViewController.viewDidLoad()
let backBarBtnItem = UIBarButtonItem()
backBarBtnItem.title = "back"
navigationItem.backBarButtonItem = backBarBtnItem
2.In the currentViewController.viewDidAppear()
let backBarBtnItem = UIBarButtonItem()
backBarBtnItem.title = "back"
navigationController?.navigationBar.backItem?.backBarButtonItem = backBarBtnItem
Reason : the backButton comes from navigationBar.backItem.backBarButtonItem,so the first way is obvious.In currentViewController.viewDidLoad(),we can't obtain the reference of backItem,because in viewDidAppear(),the navigationBar pushed navigationView on its stack.so we can make changes to the backItem in currentViewController.viewDidAppear()
For more details,you can see Document:UINavigationBar
Back button text and color text:
navigationController?.navigationBar.tintColor = .red
navigationController?.navigationBar.topItem?.backButtonTitle = "Hi"
In the viewDidLoad method of the presenting controller add:
// hide navigation bar title in the next controller
let backButton = UIBarButtonItem(title: "", style:.Plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
although these answers fix the problem but this could be some useful
class MainNavigatioController: UINavigationController {
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
// first
let backItem = UIBarButtonItem()
backItem.title = "رجوع"
self.viewControllers.last?.navigationItem.backBarButtonItem = backItem
// then
super.pushViewController(viewController, animated: animated)
}
}
Swift 4
While the previous saying to prepare for segue is correct and its true the back button belongs to the previous VC, its just adding a bunch more unnecessary code.
The best thing to do is set the title of the current VC in viewDidLoad and it'll automatically set the back button title correctly on the next VC. This line worked for me
navigationController?.navigationBar.topItem?.title = "Title"
It works for me. Swift 5
navigationItem.backButtonTitle = ""
This works for Swift 5:
self.navigationItem.backBarButtonItem?.title = ""
Please note it will be effective for the next pushed view controller not the current one on the display, that's why it's very confusing!
Also, check the storyboard and select the navigation item of the previous view controller then type something in the Back Button (Inspector).
Try this... it will work ....
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
self.title = ""
}
The above code will hide the text and show only the back arrow on navigation bar.
Swift 4
In my case the solution was to clear the navigation item of the Master View Controller before move to the Child View Controller. And set it again if it is shown again
MasterController
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.title = "Master Title"
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationItem.title = ""
}
And this is how I push a UIViewController and clear the back bar button item in the child controller:
MasterController
let childController = ChildController(collectionViewLayout: UICollectionViewFlowLayout())
childController.navigationItem.backBarButtonItem?.title = ""
navigationController?.pushViewController(childController, animated: true)
Following code can be added to a view controller from where you are pushing view controller in which you want to change back button text
Swift 5
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
For example:-
ViewController1
ViewController2
Assume we want to update back title of viewcontroller2 and we are pushing viewcontroller2 from viewcontroller1.
then you can use following code:-
let vc2 = storyboard.instantiateViewController(withIdentifier: "ViewController2")
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "your custom back button title", style: .plain, target: self, action: nil)
self.navigationController?.pushViewController(vc2, animated: true)
Set self.title = ""
before self.navigationController?.pushViewController(vc, animated: true).
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.navigationItem.title = "Notes"
let sendButton = UIBarButtonItem(title: "New", style: .plain, target: self, action: #selector(goToNoteEditorViewController))
self.tabBarController?.navigationItem.rightBarButtonItem = sendButton
}
func goToNoteEditorViewController(){
// action what you want
}
Hope it helps!! #swift 3
If you are pushing a view controller from page view controller page, you cannot update the navigation controller's back button title. To solve this create a delegate back to your parent view controller (you may also be able to traverse the view controller hierarchy back up to the parent).
Furthermore, Back buttons have a character limit. If you exceed that character limit, the system will default to "Back". It will not truncate for you. For example:
backItem.title = "Birthdays/Anniversaries" // Get's converted to "Back".
backItem.title = "Birthdays/Anniversa…" // Fits and shows as is.
for Swift 4.2
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
GOTCHA: If you are having trouble with any of the many-starred suggestions, ensure that you are registering your UITableViewCells in viewDidLoad(), not from init()
Solution checked and work in Swift 5
Below I put few solutions for different cases:
1. Remove text from back button
The best solution to remove text from back button is to add in viewDidLoad():
navigationItem.backBarButtonItem = UIBarButtonItem()
2. Set own text on back button
In case you want to set your own title, do it by setting title of backButton:
let backButton = UIBarButtonItem()
backButton.title = "My Title"
navigationItem.backBarButtonItem = backItem
3. Empty back button on all VC
If you want to create common style in entire app - to have just arrow back without text, create base VC for all your View Controllers:
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem()
}
}
Solution presented above let you customize back button in the future if you want to make some exception later, by adding additional variable and overriding it in specific ViewController, f.ex:
class BaseViewController: UIViewController {
var customBackButtonTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
var backButton = UIBarButtonItem()
if let text = customBackButtonTitle {
backButton.title = text
}
navigationItem.backBarButtonItem = backButton
}
}
There has two of different ways to Implanting  that part those are ,
 
1.
navigationItem.backButtonTitle = "Title Goes Here"
(swift 5)
 
2.
 let backButton = UIBarButtonItem()
 backButton.title = "Title Goes Here"
 self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
 

Resources