3

我想显示自定义导航栏后退按钮。我只想在上面显示图像。我想在整个应用程序中使用这个按钮,也不想在每个文件中创建这个按钮。我怎样才能??

这是我的代码:

// 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;

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

另一个代码:

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"back_arrow.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

使用此代码返回按钮图像显示在整个应用程序中。但文本“Back”也显示出来了。我怎么解决这个问题。

提前致谢。

4

1 回答 1

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;
}

然后像这样将它添加到您的导航栏...

self.navigationItem.leftBarButtonItem = [UIBarButtonItem backArrowButtonWithTarget:self action:@selector(popViewControllerAnimated:)];

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

于 2013-07-03T09:57:42.453 回答