Search code examples
iosuinavigationcontrolleruinavigationbaruibarbuttonitem

Custom UIBarButtonItem Image Offset on Navigation Bar


I want to use my own image for the Action Button in my app. I have the image sized at 30px X 30px. In my app I use the code:

UIBarButtonItem *heart = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"[email protected]"] style:UIBarButtonItemStyleDone target:self action:@selector(theactionbutton)];
self.navigationItem.rightBarButtonItem = the action;

However, the button seems too far to the left. I have attached two images to this, the first shows the original action button, and the second shows my custom image one, for comparison. Any thoughts why it is moved to the left?

enter image description here enter image description here


Solution

    1. Create Image

      UIImage *image = [UIImage imageNamed:@"image"];

    2. Create button and set background image and target action.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height); [button setBackgroundImage:image forState:UIControlStateNormal]; [button addTarget:self action:@selector(theactionbutton) forControlEvents:UIControlEventTouchUpInside];

    1. Create UIView and add button as subview

      UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ]; [view addSubview:button];

    2. Create bar button item with custom view and set it to navigation bar right item

      UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithCustomView:view]; self.navigationItem.rightBarButtonItem = actionButton;

    Note: @2x image should be of double size. If your iamgeView is of 30x30 then your Image should of 60X60. If you have 30x30 image and name as @2x it will be used as 15x15 so, make your image of double size or use it without @2x