Question

I'm adapting an iOS 6 app to iOS 7 and I'm experiencing an strange "error". In a screen there's a rightBarButtonItem with a simple image that is showed in his place. But, if the app shows an alertview, the image moves down (50 px or so) when I tap the OK button of the alertview (the only button in this alert). There's no action linked to this alertview, it's only informational.

Also, if I change the image (setImage) of the button, this image will appear out of place.

Was it helpful?

Solution

Well, I finally found myself a solution:

I had a UIBarButtonItem with UIBarButtonItemStylePlain and an image setted with setImage on the UIBarButtonItem.

To solve the issue, I have created an UIButton with the image (setting its frame with an CGRectMake) , and then I have created the UIBarButtonItem with initWithCustomView and using the UIButton as the CustomView. This way the image is always where it should be.

Edit:

UIButton* aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = CGRectMake(0.0, 40.0, 30.0, 30.0);
[aButton setBackgroundImage:[UIImage imageNamed:@"anImage.png"] forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(aFunction:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *anUIBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:aButton]; 
self.navigationItem.rightBarButtonItem = anUIBarButtonItem;

OTHER TIPS

Thanks for this raul, I've translated it into Swift for the Swift users out there:

let a = UIButton(type: .Custom)
a.frame = CGRectMake(0.0, 40.0, 30.0, 30.0)
a.setBackgroundImage(UIImage(named: "Share")!, forState: .Normal)
a.addTarget(self, action: "shareThis:", forControlEvents: .TouchUpInside)
let uiItem = UIBarButtonItem(customView: a)
self.navigationItem.rightBarButtonItem = uiItem

I had a similar issue with my right nav bar button and it went away when I removed the "title" value of the offending bar button item. In my case the title should never have been set because the button uses an image. YMMV.

I'm not sure why it matters but it fixed my issue with the bar button item getting offset on uialertcontroller dismissal.

I got my inspiration from this question: UIAlertController moves leftBarButtonItem down

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top