How do I style the backBarButtonItem title in a navigation bar? - ios

I'd like to be able to change only the text color of the back button in the navigation bar.
As a work around, I can sort of do what I'm trying to do by creating a custom view and assigning it to navigationItem.leftBarButtonItem, but it doesn't look very good and I also lose the swipe to pop ability.
Code for the above:
let button = UIButton(type: .system)
let originalImage = #imageLiteral(resourceName: "BackButton")
let scaledImage: UIImage = UIImage(cgImage: originalImage.cgImage!, scale: 30, orientation: originalImage.imageOrientation)
button.setImage(scaledImage, for: .normal)
button.setTitle("YourTitle", for: .normal)
button.sizeToFit()
button.setTitleColor(.brown, for: .normal)
button.tintColor = .blue
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
I also see things suggested like setting attributes of the back button via
navigationController?.navigationBar.topItem.backBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal)
but that doesn't seem to have any effect on the look of the text, despite
print("Attributes: ", navigationController?.navigationBar.topItem?.backBarButtonItem?.titleTextAttributes(for: .normal) ?? "No attributes")
resulting in Attributes: ["NSColor": UIExtendedSRGBColorSpace 1 0 0 1].
I could set tintColor but that would change the color of the back icon in addition to the title.
So what's the best way to do what I want? Is there a way?

Am not sure whether I understood you correctly. But try the below code. This will apply to all the bar button items of your app. Place this code where it is called only once though out app lifecycle. Like application: didFinishLaunchingWithOptions:
let attribs = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)]
UIBarButtonItem.appearance().setTitleTextAttributes(attribs, for: .normal)

I figured it out. You can style the back button by setting self.navigationItem.backBarButtonItem in the previous view controller.
For example, in my case I had TableViewController and when you clicked on a cell, the app would transition to ViewController. In TableViewController I had
public func changeColor() {
let barButton = UIBarButtonItem(title: "Anything", style: .plain, target: nil, action: nil)
barButton.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.brown], for: .normal)
self.navigationItem.backBarButtonItem = barButton
}
and then in ViewController I had
#IBAction func buttonPressed(_ sender: Any) {
let vc = self.navigationController?.viewControllers[0] as! TableViewController
vc.changeColor()
self.title = "hello very long title asdfasdfasfdasdfasdfasdfasdfasdf"
}
As a result, pressing a button in ViewController would change the color of the title of its back button to brown.

Related

UIBarButtonItem Initializer with Image and Title does not show Title

I am using init(title:image:primaryAction:menu:) of a UIBarButtonItem Apple Documentation on a Toolbar with the hope of showing a button with both image and title. Does anyone know why the title does not show?
I am not looking for a custom implementation that can add a UIBarButtonItem with title and image. I have seen plenty on Stackoverflow. I just want to use this initializer if it works.
I have a UITableViewController subclass and I have added this code to the viewDidLoad
navigationController?.isToolbarHidden = false
let barButtonItem = UIBarButtonItem(title: "New Item", image: UIImage(systemName: "plus.circle.fill"), primaryAction: nil, menu: nil)
toolbarItems = [barButtonItem]
My guess is that since public convenience init(title: String? = nil, image: UIImage? = nil, primaryAction: UIAction? = nil, menu: UIMenu? = nil) is a convenience init, and the fact that there is no init that initialize with both title and image, then using both at the same time is not supported. It's merely a convenience on using primaryAction and menu then having title and image.
Try to assign a custom button to your navBar button, declare your button under your controller class:
let myButton = UIButton(type: .system)
now in viewDidLoad set your custom button with title and assign it to navigation bar:
myButton.setImage(UIImage(systemName: "square.and.arrow.up"), for: .normal)
myButton.setTitle(" your text", for: .normal)
myButton.sizeToFit()
myButton.addTarget(self, action: #selector(yourFunctionAction), for: .touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: myButton)

iOS : BackbarButton

Hi I saw too many tutorial from stack overflow for how to change backBarButton I change it but when I check I see my image(custom arrow) beside (default arrow blue one ) I see both beside of each other
I mean the back text changed but the arrow doesn't I see my custom arrow beside default iOS arrow I don't know how should I change it to see my custom arrow only ???
for more detail please check this picture to see this problem
HERE
First You need to hide the default back Button , then supply your Custom one. Following code will help you.
self.navigationItem.hidesBackButton = true
let back: UIButton = UIButton(type: UIButtonType.custom)
back.setImage(UIImage(named: "backarrow"), for: UIControlState.normal)
back.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
back.addTarget(self, action: #selector(self.backPressed), for: UIControlEvents.touchUpInside)
let left: UIBarButtonItem = UIBarButtonItem(customView: back)
self.navigationItem.setLeftBarButton(left, animated: true)
self.navigationController?.navigationBar.topItem?.title = ""
func backPressed() {
//Do your menupulation
}
If I understand you correctly you just need to place your button into Navigation Bar and then set your image name into "image" field.
http://take.ms/Rfrtf - here is for example ;)
Solution 1
You can set default back button color's tint color to red .
UINavigationBar.appearance().tintColor = UIColor.red // add this line appdelegate
Solution 2
self.navigationItem.leftItemsSupplementBackButton = YES;
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
or
self.navigationItem.leftBarButtonItems = #[customBackButtonItem];

Swift strange back button text in iphone plus

Please take a look at my screenshot, the blue "Back" text always show on iphone plus (6s plus, 7 plus for both simulator and real device) . It does not show on smaller screen iphone. I tried lot of way to hide/change it from present/previous controller but no luck.
So why does it work on smaller iphone but not the plus one ?
Can anyone help me:(. Thanks.
Here is the code:
#IBAction func filter(_ sender: Any) {
let view:FilterViewController = self.storyboard?.instantiateViewController(withIdentifier: "FilterViewController") as! FilterViewController
view.superVC = self
view.currentFilter = currentFilter
self.setLeftCloseNavigation()
self.navigationController?.pushViewController(view, animated: true)
}
func setLeftCloseNavigation(){
self.navigationController?.navigationBar.backgroundColor = UIColor.clear
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.layer.mask = nil
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "icon_close")?.withRenderingMode(.alwaysOriginal)
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "icon_close")?.withRenderingMode(.alwaysOriginal)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
And here is the viewDidLoad in pushed controller:
override func viewDidLoad() {
super.viewDidLoad()
statusBar = UIColor.black
setResetNavigation() }
func setResetNavigation(){
navigationItem.hidesBackButton = false
let skipButton = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 30))
skipButton.setTitle("Reset all".localized(), for: .normal)
skipButton.setTitleColor(UIColor.black, for: .normal)
skipButton.titleLabel?.font = UIFont(name: "HJGothamMedium", size: 16)
skipButton.addTarget(self, action: #selector(resetAllClicked), for: .touchUpInside)
let skip = UIBarButtonItem(customView: skipButton)
navigationItem.rightBarButtonItem = skip
}
This is the view hierarchy
Add this function :
override func viewDidAppear(_ animated: Bool) {
setResetNavigation()
self.navigationController?.navigationBar.backItem?.title = ""
}
try this
self.navigationItem.hidesBackButton = true
Or Check your storyboard it will remain
Use the below line to remove the text
navigationController?.navigationBar.topItem?.title = ""
You can inspect your UI hierarchy and if found related view then remove that view :
You can also invoke the view debugger by choosing View UI Hierarchy from the process view options menu in the debug navigator, or by choosing Debug > View Debugging > Capture View Hierarchy.
To hide the back text you need to set navigation item title to space character on the view controller that pushes the presented view controller:
self.navigationItem.title = " "
Be aware you have to set it on the previous view controller and not on top most one. Also you have to set a space character and not an empty string !!!
Also you can do this directly on storyboard
From below code you can set backButton text colour to any colour you want.You can simply set backButton to clear textColor. So, It won't be visible when it presents.
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.classForCoder() as! UIAppearanceContainer.Type]).setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
Update: If you want to go for a different approach.Check this post How to customize the navigation back symbol and navigation back text? and accepted answer.

UINavigation set back button image instead of the <Back text Swift 2.0

I am trying to change the Back button within the UINavigationController. This is what I tried so far and the output:
1
Code within the ViewDidLoad
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "navBarBackButton")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "navBarBackButton")
self.navigationItem.backBarButtonItem?.image = UIImage(named: "navBarBackButton")
Output:
I tried to add the below but id didn't help:
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Plain, target:nil, action:nil)
2
Code within the AppDelegate
let backImg: UIImage = UIImage(named: "navBarBackButton")!
UIBarButtonItem.appearance().setBackButtonBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)
Output:
3
I tried to add the back button in Storyboard but nothing changed
4 - Thanks to sanandiya vipul. Still need it to be instead of the 'Back'. This only deletes the 'Back but keeps the image lower right side instead of the entire '
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), forBarMetrics: .Default)
This is the output:
This is the result I am hoping to achieve
Below Code add your ViewDidLoad method. its work for you fine.
for Swift
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), forBarMetrics: .Default)
for Objective-c
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0,- 80.f) forBarMetrics:UIBarMetricsDefault];
Swift 4 version
Set Back title text color to clear
let barButtonItemAppearance = UIBarButtonItem.appearance()
barButtonItemAppearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.clear], for: .normal)
barButtonItemAppearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.clear], for: .highlighted)
Just added UIBarButtonItem and linked it to action.
#IBAction func backTapped(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
Swift 5 version
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -80.0), for: .default)

custom barbuttonItem doesn't show up

I have made a custom bar button item at my navigation controller and it was working fine but it doesn't anymore.
This is the lines that I use to make the custom bar button :
func addSlideMenuButton(){
let btnShowMenu = UIButton(type: UIButtonType.Custom)
//btnShowMenu.setImage(self.defaultMenuImage(), forState: UIControlState.Normal)
btnShowMenu.setImage(UIImage(named: "barBtnMenu"), forState: UIControlState.Normal)
btnShowMenu.frame = CGRectMake(0, 0, 30, 30)
btnShowMenu.addTarget(self, action: "onSlideMenuButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
let customBarItem = UIBarButtonItem(customView: btnShowMenu)
// self.navigationItem.rightBarButtonItem = customBarItem;
self.navigationItem.leftBarButtonItem = customBarItem;
}
the image exists and there is no error or crash .
Even If I add the bar button item from soryboard , When I run the application it would hidden my bar button item.
What could be wrong ?
func addSlideMenuButton() {
let customBarItem = UIBarButtonItem(image: UIImage(named: "barBtnMenu"), style: .Plain, target: self, action: "onSlideMenuButtonPressed")
self.navigationItem.leftBarButtonItem = customBarItem;
}
A couple of options come to mind
Are you sure you're not setting navigationItem.hidesBackButton = true anywhere in that UIViewController?
Are you sure you're not adding another UINavigationBar on top of the one provided by the system?

Resources