[英]set background image of navigation's bar item
In my UINavigationController I have added an add button through the storyboard. 在我的UINavigationController中,我通过情节提要添加了一个添加按钮。 My add button is the default "+"
UIBarButtonItem
from iOS/xcode. 我的添加按钮是iOS / xcode中默认的“ +”
UIBarButtonItem
。 I would like to add a custom background image to the button. 我想向按钮添加自定义背景图片。 My codes is not working: the background image is not added.
我的代码不起作用:未添加背景图片。
-(void)addBackgroundToPlusSign
{
UIImage *addBkg = [UIImage imageNamed:@"plus_sign"];
addBkg = [addBkg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[self.navigationItem.rightBarButtonItem setBackButtonBackgroundImage:addBkg forState:UIControlStateNormal barMetrics:0];
}
I try calling the method in viewDidLoad
and then in viewWillAppear
. 我尝试在
viewDidLoad
然后在viewWillAppear
调用该方法。 No luck. 没运气。
Your issue is that you are setting the back button's background image on the right nav button... The right navigation button is not the back button. 您的问题是您要在右侧导航按钮上设置后退按钮的背景图像...右导航按钮不是后退按钮。 From the documentation:
从文档中:
This modifier applies only to navigation bar back buttons and is ignored by other buttons.
此修饰符仅适用于导航栏后退按钮,其他按钮将忽略它。
You want to use setBackgroundImage:forState:barMetrics:
您要使用
setBackgroundImage:forState:barMetrics:
You can add UIImageView or button example: 您可以添加UIImageView或按钮示例:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 70, 30)];
[button setImage:[UIImage imageNamed:@"plus_sign"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(your_method) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.rightBarButtonItem = buttonItem;
try doing: 尝试做:
UIBarButtonItem * addBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(btnHandler:)];
UIImage *addBkg = [UIImage imageNamed:@"plus_sign"];
addBkg = [addBkg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[addBtn setBackgroundImage:addBkg forState:UIControlStateNormal barMetrics:0];
self.navigationItem.rightBarButtonItem = addBtn;
I think there used to be a bug where setting the background of an existing button didn't work until the view was re-added to the view stack. 我认为以前存在一个错误,即在将视图重新添加到视图堆栈之前,设置现有按钮的背景不起作用。 You could also try just doing:
您也可以尝试做:
self.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.