简体   繁体   English

将后退按钮的背景更改为与导航栏相同

[英]change background of back button to the same as navigation bar

I am trying to implement a custom image for the navigation bar and buttons on it. 我正在尝试为导航栏和其上的按钮实现自定义图像。 I managed to get the correct setup for my nav background using this 我设法使用此为我的导航背景获取正确的设置

这是下面的代码会发生的情况

        - (void)customAppearance
{  
    UIImage* NavBG = [UIImage imageNamed:@"header.png"];
    [[UINavigationBar appearance] setBackgroundImage:NavBG forBarMetrics:UIBarMetricsDefault];
}

but when i try to do something similar for the back button or other button it all just blends together (I can see the words of the back button but no outline for the back button is present) 但是当我尝试为后退按钮或其他按钮执行类似操作时,它们都融合在一起(我可以看到后退按钮的文字,但没有后退按钮的轮廓)

here is what i have for the back button 这是我的后退按钮

UIImage *backButtonBG = [[UIImage imageNamed:@"header.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonBG forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

and i want to get it looking like this: 我想让它看起来像这样: 目标是什么

I think that the easiest way is for you to also tint the navigation bar, because the default is that those bar butons items always use the color of the navigation bar. 我认为最简单的方法是对导航栏进行着色,因为默认情况下,这些栏按钮项始终使用导航栏的颜色。

[[UINavigationBar appearance] setTintColor:[UIColor redColor]];

or u can use a more precise color using rgb values 或者您可以使用rgb值使用更精确的颜色

[[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:val green:val blue:val alpha:1]];

I created my tinted button using a custom image (see code at the end) Then just set the leftBarButtonItem to this button. 我使用自定义图像创建了有色按钮(请参见最后的代码),然后将leftBarButtonItem设置为此按钮。

+ (UIBarButtonItem *)createBarButtonItemWithImage:(UIImage *)normalImage highlightedImage:(UIImage *)highlightedImage
{
    UIBarButtonItem *barButtonItemToReturn;
    if (normalImage == nil && highlightedImage == nil)
    {
        return barButtonItemToReturn;
    }
    else if (normalImage != nil)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:normalImage forState:UIControlStateNormal];

        if (highlightedImage != nil)
        {
            [button setImage:highlightedImage forState:UIControlStateHighlighted];
            [button setFrame:CGRectMake(0, 0, normalImage.size.width, normalImage.size.height)];
        }

        barButtonItemToReturn = [[UIBarButtonItem alloc] initWithCustomView:button];
    }
    return barButtonItemToReturn;
}

When you want to add a target/action, you have to add it via: 当您要添加目标/操作时,必须通过以下方式添加目标/操作:

 [((UIButton*)barButtonItem.customView) addTarget:self selector:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];

You can also use a resizable image, etc 您还可以使用可调整大小的图像等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM