我正在尝试在rightBarButtonItem上设置图像并且它很好,但唯一不对的是这个图像背后的背景,它的宽度比我的图像宽。 任何人都知道如何解决这个问题。 代码:
[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"action_btn.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(actionButtonClicked:)] animated:YES];
答案 0 :(得分:19)
您可以在此处设置NavigationBar的rightBarButtonItem上的图像,如下所示:
UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,105,30);
[button1 setBackgroundImage:[UIImage imageNamed: @"image1.png"] forState:UIControlStateNormal];
[button1 addTarget:appDelegate action:@selector(Open_Link1) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
[button1 release];
如果您有任何其他问题,请与我们联系。
答案 1 :(得分:3)
在 Swift :
let infoImage = UIImage(named: "my-icon")
let imgWidth = infoImage?.size.width
let imgHeight = infoImage?.size.height
let button:UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: imgWidth!, height: imgHeight!))
button.setBackgroundImage(infoImage, forState: .Normal)
button.addTarget(self, action: Selector("openInfo"), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
P.S。 UIBarButtonItem(image:style:target:action:)
构造函数仅适用于透明PNG,我还必须设置除clearColor之外的按钮tintcolor。
答案 2 :(得分:-1)
我现在不在XCode中,所以我无法发布代码。 程序就像这样
如果它与100%不匹配,请考虑在设置按钮的框架之前将按钮的边界添加到图像尺寸