Custom Back Button With Image

2019-03-05 23:44发布

问题:

What I'd like to do is alter the height of the back button. However, as I understand it, the only option to alter is width. So, I thought I'd create a custom back button with my own, smaller, image. Now I've done this using the viewDidLoad method with the code below:

//Setup navigation bar
        navigationController?.navigationItem.backBarButtonItem = UIBarButtonItem(image:UIImage(named:"back_arrow.png"), style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
        navigationController?.navigationItem.backBarButtonItem!.title = ""

However, the back button remains blue, large, and has the title 'Back'. How can I get this code to work properly? The debugger says it is running, but it is not changing anything.

回答1:

For color you have to set the tint color on navBar, also you can set navigationItem.backBarButtonItem to nil and use leftbarButtonItem with custom button image.



回答2:

I'm going to show you how to do this in the entire app, not just one page.

To change the default image of the back button, put the following in your app delegate didFinishLaunchingWithOptions::

Swift:

let backArrowImage = UIImage(named: "customImage")
let renderedImage = backArrowImage?.imageWithRenderingMode(.AlwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = renderedImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = renderedImage

Obj-c:"

UIImage *backArrowImage = [UIImage imageNamed:@"customImage"];
UIImage *renderedImage = [backArrowImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[UINavigationBar appearance].backIndicatorImage = renderedImage;
[UINavigationBar appearance].backIndicatorTransitionMaskImage = renderedImage;

To remove the "Back" text from the button, add this category to your AppDelegate.m file (or your own category):

Not sure how to do this in Swift yet, so here's the Obj-c version:

@implementation UINavigationItem (LuxeCustomization)

/**
 Removes text from all default back buttons so only the arrow or custom image shows up
 */
-(UIBarButtonItem *)backBarButtonItem
{
    return [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

@end