Setting a UIImage to a UIBarButton item

南笙酒味 提交于 2019-12-02 08:29:18

To call

self.navigationItem.leftBarButtonItem = [CustomBarButton createNavBackBarButtonItemWithTitle:NSLocalizedString(@"Back", @"") target:self action:@selector(actionBack:)];

CustomBarButton has createNavBackBarButtonItemWithTitle class function

+(UIBarButtonItem *)createNavBackBarButtonItemWithTitle:(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:@"back_button_up.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];
UIImage *buttonPressedImage = [[UIImage imageNamed:@"back_button_over.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];


[[button titleLabel] setFont:[UIFont boldSystemFontOfSize:12.0]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] 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:[NSString stringWithFormat:@"  %@",t] forState:UIControlStateNormal];

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

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

return [buttonItem autorelease];
}

You have to set the buttonStyle to custom not a UIBarButtonItemStylePlain

and then [barbuttonitem setCustomView:anImageView];

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!