自定义导航栏后退按钮,仅带图像

shi*_*vam 3 objective-c uinavigationcontroller ios

我想显示自定义导航栏后退按钮.我想只显示图像.我想在整个应用程序中使用此按钮也不想在每个文件中创建此按钮.我怎么能够??

这是我的代码:

// Set the custom back button
        UIImage *buttonImage = [UIImage imageNamed:@"back_arrow.png"];

        //create the button and assign the image
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:buttonImage forState:UIControlStateNormal];

        //set the frame of the button to the size of the image (see note below)
        button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

        [button addTarget:self action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];

        //create a UIBarButtonItem with the button as a custom view
        UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.navigationItem.leftBarButtonItem = customBarItem;
Run Code Online (Sandbox Code Playgroud)

但这仅在当前页面上显示.

另一个代码:

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"back_arrow.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)

使用此代码后退按钮图像显示在整个应用程序中.但文字"后面"也在显示.我怎么解决这个问题.

提前致谢.

Fog*_*ter 11

我过去曾用过一个类别来做这件事.

在UIBarButtonItem上创建一个名为+ projectButtons(或其他东西)的类别.

然后你可以有一个像...这样的功能

+ (UIBarButtonItem)backArrowButtonWithTarget:(id)target action:(SEL)action
{
    UIImage *buttonImage = [UIImage imageNamed:@"back_arrow.png"];

    //create the button and assign the image
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];

    //set the frame of the button to the size of the image (see note below)
    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    //create a UIBarButtonItem with the button as a custom view
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    return customBarItem;
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到导航栏中,就像这样......

self.navigationItem.leftBarButtonItem = [UIBarButtonItem backArrowButtonWithTarget:self action:@selector(popViewControllerAnimated:)];
Run Code Online (Sandbox Code Playgroud)

这意味着您只需要一行代码来创建它,但您仍然可以在您使用它的每个VC中自定义目标和操作.如果您决定更改按钮的外观,那么它们都在一个地方完成.