使用背景图像自定义UIBarbuttonitem

Tai*_*mal 3 iphone cocoa-touch uitoolbar uibarbuttonitem uibarbuttonitemstyle

我在它上面添加了一个UIToolbar和按钮的实例.每个按钮属于UIBarButtonItem类.

我的要求是每个按钮都有一个自定义的布局,我不想使用Apple提供的原生按钮样式.所以我在Interface Builder中有3个选项(Plain,Bordered,Done).我选择了Plain样式,并在Bar item - > Image下选择了我要添加为背景的图像.

但它对我没有用,使用普通选项使我更接近边界和完成距离更近但仍然显示白色轮廓的图像.无论如何,按钮上的图像被添加,它们看起来完全一样.使用UIButton时,这是一项非常简单的任务.我刚刚在UIButton的Attributes检查器中使用了Image选项,并选择了我想要的图像.但是在这里使用UIBarButtonitem它根本不起作用.这就是它的显示方式

谢谢泰穆尔

Mic*_*Fey 24

泰穆尔,

我遇到了你遇到的同样问题.我们的设计师在我们的应用程序导航栏中为按钮指定了自定义外观.这是我编写的实用方法,用于生成我们需要的UIBarButtonItems,您应该能够根据需要对其进行修改:

+ (UIBarButtonItem *)createSquareBarButtonItemWithTitle:(NSString *)t target:(id)tgt action:(SEL)a
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    // Since the buttons can be any width we use a thin image with a stretchable center point
    UIImage *buttonImage = [[UIImage imageNamed:@"SquareButton.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];
    UIImage *buttonPressedImage = [[UIImage imageNamed:@"SquareButton_pressed.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];

    [[button titleLabel] setFont:[UIFont boldSystemFontOfSize:12.0]];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button setTitleShadowColor:[UIColor colorWithWhite:1.0 alpha:0.7] forState:UIControlStateNormal];
    [button setTitleShadowColor:[UIColor clearColor] forState:UIControlStateHighlighted];
    [[button titleLabel] setShadowOffset:CGSizeMake(0.0, 1.0)];

    CGRect buttonFrame = [button frame];
    buttonFrame.size.width = [t sizeWithFont:[UIFont boldSystemFontOfSize:12.0]].width + 24.0;
    buttonFrame.size.height = buttonImage.size.height;
    [button setFrame:buttonFrame];

    [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [button setBackgroundImage:buttonPressedImage forState:UIControlStateHighlighted];

    [button setTitle:t forState:UIControlStateNormal];

    [button addTarget:tgt action:a forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    return [buttonItem autorelease];
}
Run Code Online (Sandbox Code Playgroud)