代码之家  ›  专栏  ›  技术社区  ›  cdub

在ios 7中更改UIBarButtonItem的背景色

  •  2
  • cdub  · 技术社区  · 10 年前

    我有一个UINavigationBar和一个右UIBarButtonItem。

    如何仅更改按钮的背景色(而不是文本)?

    UIBarButtonItem *postButton = [[UIBarButtonItem alloc] initWithTitle:@"POST" style:UIBarButtonItemStylePlain target:self action:@selector(postButtonPressed:)];
    
    // Changes text color
    postButton.tintColor = [UIColor blueColor];
    

    如何更改背景色?

    3 回复  |  直到 10 年前
        1
  •  3
  •   mustafa    7 年前

    使用故事板或XIB,您可以将UIButton直接添加到导航栏并更改UIButton背景色。

    enter image description here

    enter image description here

        2
  •  2
  •   Rukshan    10 年前

    使用 appearance 代理此,

    使用您喜欢的颜色创建1x1像素图像。在本例中,此图像的名称为“icons_gb.png” AppDelegate.m 。图像颜色将在按钮的背景中重复。

    UIImage *btnBg = [[UIImage imageNamed:@"icons_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    [[UIBarButtonItem appearance] setBackgroundImage:btnBg 
                                            forState:UIControlStateNormal
                                          barMetrics:UIBarMetricsDefault];
    
        3
  •  0
  •   Quang Hà    10 年前

    您可以通过以下方式进行更改:

    yourNavigationBar.barTintColor = [UIColor yellowColor];
    

    导航栏的颜色也可以更改。

    如果您只想更改UIBarButtonItem,请使用我的自定义类:

    UIBarButtonItem+自定义.h

    #import <UIKit/UIKit.h>
    
    @interface UIBarButtonItem (Custom)
    + (UIBarButtonItem *) barItemWithImage:(UIImage *)img size:(CGSize)size target:(id)target action:(SEL)selector;
    @end
    

    UIBarButtonItem+自定义.m

    #import "UIBarButtonItem+Custom.h"
    
    @implementation UIBarButtonItem (Custom)
    + (UIBarButtonItem *) barItemWithImage:(UIImage *)img size:(CGSize)size target:(id)target action:(SEL)selector
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
        [button setImage:img forState:UIControlStateNormal];
    
        button.frame= CGRectMake(0.0, 0.0, size.width, size.height);
    
        [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    
        UIBarButtonItem *forward = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
    
        return forward;
    }
    @end