在我的UINavigationController中,我在故事板中添加了一个添加按钮。我的添加按钮是来自iOS / xcode的默认“+”UIBarButtonItem
。我想在按钮上添加自定义背景图像。我的代码不起作用:未添加背景图片。
-(void)addBackgroundToPlusSign
{
UIImage *addBkg = [UIImage imageNamed:@"plus_sign"];
addBkg = [addBkg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[self.navigationItem.rightBarButtonItem setBackButtonBackgroundImage:addBkg forState:UIControlStateNormal barMetrics:0];
}
我尝试在viewDidLoad
中调用该方法,然后在viewWillAppear
中调用该方法。没有运气。
答案 0 :(得分:1)
您的问题是您在右侧导航按钮上设置了后退按钮的背景图像...右侧导航按钮不是后退按钮。来自文档:
此修饰符仅适用于导航栏后退按钮,并且是 被其他按钮忽略。
您想使用setBackgroundImage:forState:barMetrics:
答案 1 :(得分:0)
您可以添加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;
答案 2 :(得分:0)
尝试做:
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;
我认为曾经存在一个错误,即在将视图重新添加到视图堆栈之前,设置现有按钮的背景并不起作用。你也可以尝试一下:
self.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem;