Cant set image for UIBarButtonItem

旧城冷巷雨未停 提交于 2019-12-03 12:55:46

try this ... change it's method, image according to you

UIButton *button1=[UIButton buttonWithType:UIButtonTypeCustom];
[button1 setFrame:CGRectMake(10.0, 2.0, 45.0, 40.0)];
[button1 addTarget:self action:@selector(showLeft:) forControlEvents:UIControlEventTouchUpInside];
[button1 setImage:[UIImage imageNamed:@"left-arrow-button.png"] forState:UIControlStateNormal];
UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithCustomView:button1];
self.navigationItem.leftBarButtonItem = button;

I have modified your code and tested the image showing in the barbutton. Please try this by yourself. And please let me know if you face any problem on this.

    UIImage *faceImage = [UIImage imageNamed:@"Badge.png"];
    UIButton *face = [UIButton buttonWithType:UIButtonTypeCustom];
    face.bounds = CGRectMake( 0, 0, faceImage.size.width, faceImage.size.height );
    [face addTarget:self action:@selector(showAlerts) forControlEvents:UIControlEventTouchUpInside];
    [face setImage:faceImage forState:UIControlStateNormal];
    UIBarButtonItem *faceBtn = [[UIBarButtonItem alloc] initWithCustomView:face];    
    self.navigationItem.leftBarButtonItem = faceBtn;

EDIT: I have added a line in my answer. I just printed a message "Hi" in log. it is working. Can you please try it?

Thanks.

clearlight

Or... just write two lines of iOS 8 Swift code. (Might even work in iOS 7)

    let doneButtonAsLeftArrow = UIBarButtonItem(image: UIImage(named: "LeftArrow24x24.png"), style: .Plain, target: self, action: "doneButtonPushed")
    navigationItem.leftBarButtonItem = doneButtonAsLeftArrow

Swift version of accepted answer for anyone

var settingsButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
settingsButton.frame = CGRect(origin: CGPointZero, size: CGSize(width: 36, height: 36))
settingsButton.setImage(image, forState: UIControlState.Normal)
settingsButton.addTarget(self, action: "buttonActionHere:", forControlEvents: UIControlEvents.TouchUpInside)

let rightBarButtonItem = UIBarButtonItem(customView: settingsButton)
navigationItem.setRightBarButtonItem(rightBarButtonItem, animated: true)
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithImage:faceImage style: UIButtonTypeCustom target:self action:@selector(addProduct:)];

    self.navigationItem.leftBarButtonItem = addButton;

u were creating a default button, you need to create a UIButtonTypeCustom type button...

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