This question already has answers here:
Setting action for back button in navigation controller
(29 answers)
Closed 7 years ago.
I want to add an Action to my standard Back-Button, but this won't work as I found from below link:
add-target-to-stock-back-button-in-navigationbar
So I created a custom button with an action.
UIBarButtonItem(title: "❮ Back", style: .Bordered, target: self, action: "back:")
But how can I set the standard left wing to the title?
The character '❮' is way smaller than that from the standard button. I use the standard button throughout my app, and I want to keep this optic.
If you want to "add" some functionality to your back button you can use the UINavigationControllerDelegate.
When you press the back button, the navigation controller will call navigationController(willShowViewController:) so you can use this to do whatever you want to do. An example is shown below:
Using UINavigationControllerDelegate:
class ViewController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
// Add whatever you want to do here
}
}
Related
I have an existing navigation controller delegate that places a menu button on each view controller in the app.
class MyNavigationControllerDelegate: NSObject, UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let navItem = viewController.navigationItem
let menuBtn = MyCustomMenuButton()
...
navItem.setRightBarButton(menuBtn, animated: false)
}
This works great...I get a menu button in the nav bar for each view. But for some views, I'd like to add another button on the right next to the menu button, so I added this:
class CustomViewController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let newButton = UIBarButtonItem(title: "(+)", style: .plain, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = newButton
}
}
But this has no effect. The menu button is still there but the new button is not added. How should this be done then?
But this has no effect
Yes, it does. But you don't have time to see the effect. You are saying the same thing twice, because setRightBarButtonItem is the same as rightBarButtonItem =... So whichever one you say second, that is the one that is ultimately obeyed; either way, it rips the existing right bar button item out and replaces it with the other one.
If the goal is to have multiple right bar button items, that is what the rightBarButtonItems is for (notice the plural). You can call setRightBarButtonItems instead (again, notice the plural). Looking to see whether there is already a right bar button item and taking that into account is up to you, of course. There is no magical append method.
I have multiple view controllers embedded inside a navigation controller. I have an option that changes the language of the user interface. When user chooses French, the user interface should update itself with French language. All elements are updated with French as I expected, except the button that takes user back to the previous view controller (as you can see in the screenshot - "List of Events").
This is the function I call to update UI :
func updateView() {
DispatchQueue.main.async {
// CurrentSelection.LanguageUI holds a reference to currenly selected language object
navigationItem.title = CurrentSelection.languageUI.event_singular
navigationController?.title = CurrentSelection.languageUI.listOfEvents <<- this line doesn't work
}
}
The navigationController?.title holds "List of Events" string and the assignment statement seems to work. It just that the UI isn't updated with the new title value. Where am I doing wrong?
It's the previousVC that decides what it's own back button will be.
So set this on the previousVC in viewDidLoad
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Back title" style:UIBarButtonItemStylePlain target:nil action:nil];
If this isn't set then the back button will be the .title of the previous VC.
-
In your situation you should have some kind of language change notification that the previous VC can listen for and know to update its own title.
One way to do it is to implement UINavigationControllerDelegate and set the back bar button item there:
class YourViewController: UIViewController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
// MARK: - Navigation controller delegate
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: "Custom title", style: .plain, target: nil, action: nil)
viewController.navigationItem.backBarButtonItem = item
}
}
Something to be aware of is that this needs to be implemented in the view controller which pushes the next view controller. So you'll be changing the back bar button item of the view controller that willShow.
Those view controllers in the navigation stack won't change atomatically.
So you have to use Notification center and add observers to the previous view controllers and change the Title of the navigation bar with selected language when it is called.
When language is changed you have to post the change.
Then it will change the title to french so does the back button will
change.
I am building a mobile app which displays stats from multiple APIs.
The app shows different values based on the API that is active. At runtime, the user can select which API to display values for. However, the values are always displayed within the same Target view controller.
UINavigationController is in use and I'd like to defer to that for navigation and navigation UI, if possible, even though UITableViewControllers support navigation bars.
Please see the storyboard design image at the end of the question.
Environment: iOS 9/Swift 2.2/XCode 7
At runtime, the user will select a Choice view controller from the Select controller. What is the appropriate way to segue from one of the Choice view controllers, via a "Done" UIBarButton, to the Target controller? The Target controller does not change.
Must I programmatically define the right bar button to "Done" for every controller that is embedded within the UINavigationController?
class UIViewController: UITableViewController {
override func viewWillAppear( animated: Bool) {
super.viewWillAppear( animated)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
}
}
The proper way to return to the root view controller is:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(MyViewController.done))
}
func done() {
if let navigationController = self.navigationController {
navigationController.popToRootViewController(animated: true)
}
}
}
You do need to programmatically add a "done" button; but it's more simple than that. Just select your root view controller, and copy/past the class in storyboard. Use your segues to push the correct view onto the UINavigation stack.
This question already has answers here:
Removing the title text of an iOS UIBarButtonItem
(39 answers)
Closed 7 years ago.
I do not want to see the "Back" text that is displayed automatically when going to a view controller with no Title. I would like this to happen everywhere on my application, is there a few lines of code I can put in the app delegate to make this possible?
I have tried a few approaches from SO before posting this question and have found no success. I want to this in Swift, not Obj-c.
I tried this with no success; it ran fine, but the back text was still displayed in the next view controller.
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
}
I would like to put this in app delegate so it would happen throughout my application rather than having to put that into every single swift file in my project. Anybody have any ideas?
There are several different ways to do this. I’ll present a solution that gives you a bit more flexability as you’ll want to display a button some times, hide other times, and customize at other times. This example assumes you are using Navigation Controller based UI, but can be adapted to other types.
Whenever I create an app I like to create my own UIViewController class and have all of my UIViewControllers inherit from this single view controller. If I want to customize something for all my UIViewControllers I can do this at my new super class level since all the other views inherit from that.
In my sample code below I create my custom UIViewController called MasterViewController. I have all of my UIViewControllers inherit from it: ViewController, ViewController2 & ViewController3. Read the notes in the code below to understand what’s going on.
NOTE: Make sure you check for the case where the UIViewController should not have the back button as this would be the case where there is nothing to return to. You can add this code to MasterViewController but I did not for this sample.
//=========================================================
//MasterViewController
//=========================================================
// Master View Controller that all UIViewControllers inherit from.
import UIKit
class MasterViewController: UIViewController {
// This will be title if the user doesn't change it in a subclass.
var backButtonTitle = "Default Back Title"
override func viewDidLoad() {
// This resets the default back button to always be shown unless the user calls createCustomBackButtonWithTitle from child class.
self.navigationItem.hidesBackButton = false
super.viewDidLoad()
}
func createCustomBackButtonWithTitle(customTitle: String) {
// Hide the default back button.
self.navigationItem.hidesBackButton = true
// Programmatically create custom back button.
let backButton = UIBarButtonItem(title: customTitle, style: UIBarButtonItemStyle.Plain, target: self, action: "goBack:")
self.navigationItem.leftBarButtonItem = backButton
}
#IBAction func goBack(sender: UIButton!) {
navigationController?.popViewControllerAnimated(true)
}
}
//=========================================================
//ViewController
//=========================================================
// This view controller customizes the back name and inherits the default "go back" behavior from MasterViewController.
import UIKit
class ViewController: MasterViewController {
override func viewDidLoad() {
super.viewDidLoad()
createCustomBackButtonWithTitle("ButtonName")
}
}
//=========================================================
//ViewController2
//=========================================================
// This view controller customizes the back name but overrides the default "goBack" behavior from MasterViewController to do something different
import UIKit
class ViewController2: MasterViewController {
override func viewDidLoad() {
super.viewDidLoad()
createCustomBackButtonWithTitle("ButtonName 2")
}
// Override the back button behavior from super class because we don't want default "back" behavior.
#IBAction override func goBack(sender: UIButton!) {
// Costume Code here
}
}
//=========================================================
//ViewController3
//=========================================================
// This view controller inherits from MasterViewController, but gets the default "back" behavior from a normal
// UINavigationController since it never calls createCustomBackButtonWithTitle to change the behavior
import UIKit
class ViewController3: MasterViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Most people wind up doing something like #xdeleon suggested, but I highly recommend not doing that, if for no other reason that that you'll break the built-in swipe behavior to navigate backwards in the view controller stack. There are a couple answers on SO that tell you how to restore this back-swipe functionality, but as someone who's had to fix this in an existing app with 200+ view controllers, I'd like to save you a lot of pain.
If you don't mind working in storyboards, then make sure that each of your view controllers' navigation item's back button text is an empty string. However, since that's a lot to keep track of, it's marginally easier to do in code, and the only way I've found works perfectly is to create a cachedTitle instance variable on your view controller, and implement the view controller's viewWillAppear() and viewWillDisappear() methods like so:
override func viewWillAppear(animated: Bool) {
// Reset the view controller's title only if it doesn't already have one.
if (navigationItem.title == nil || navigationItem.title == "") && navigationItem.titleView == nil {
navigationItem.title = cachedTitle
}
}
override func viewWillDisappear(animated: Bool) {
if navigationItem.title != nil { // not 'if let'!
cachedTitle = navigationItem.title
navigationItem.title == ""
}
}
You can either put these methods in a UIViewController subclass that all of your view controllers extend, or, better yet, put these in custom methods in a category on UIViewController, and just call them in your view controllers' viewWillAppear() and viewWillDisappear() calls.
If you want to use something other than the back button's '<' symbol, don't add a custom back or left button; just set a custom back indicator image and mask on the navigation bar.
I have a question regarding the navigation bar.
As far as I understand from iOS: A view controller opened by a segue inherits the navigation bar of the parent view controller. Is this correct so far?
Is there a view controller within a stack "owns" the navigation bar in a complex segue stack (e.g. TableViewController that opens a TabBarController that opens ...)?
I very often run into the problem that I don't know where to get the actual navigation item in order to set the title or a bar button item.
In this case, I have the following controllers:
TabBarController
EventPostsViewController -> To display a list of posts, is a tabbed view within the TabBarController
CreatePostViewController -> To write a new post
So within the EventPostsViewController I can do this (and it works):
class EventPostsViewController: UITableViewController {
...
override func viewWillAppear(animated: Bool) {
...
// This solution works, but only for EventPostsViewController
self.tabBarController?.navigationItem.title = "text"
But within the CreatePostViewController, which is opened by a segue via EventPostsViewController, neither of this solutions work.
class CreatePostViewController: UIViewController {
...
override func viewWillAppear(animated: Bool) {
...
// Neither of these solutions works
self.navigationItem.title = "Text"
self.tabBarController?.navigationItem.title = "Text"
self.navigationController?.navigationItem.title = "Text"
How do I get the actual navigation bar/navigationItem?
Stupid simple mistake I repeat every time :)
I forgot to link my custom CreatePostViewController with the view controller using the interface builder.
This code now works:
class CreatePostViewController: UIViewController {
...
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
self.navigationController?.setNavigationBarHidden(false, animated: false)
// Set title
self.navigationItem.title = "Write Post"
// Add Submit button
var submitButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "submitPost:")
self.navigationItem.rightBarButtonItem = submitButton
}
...
}