Search code examples
iphoneobjective-cuibarbuttonitemuiappearance

UIBarButtonItem:setBackgroundVerticalPositionAdjustment not working properly with custom button


I have the following code to customize the display of an UIBarButtonItem (locationButton):

    UIButton *locationButtonAux = [UIButton buttonWithType:UIButtonTypeCustom];
    [locationButtonAux setFrame:CGRectMake(0, 0, LOCATION_BUTTON_WIDTH, LOCATION_BUTTON_HEIGHT)];
    [locationButtonAux setBackgroundImage:[UIImage imageNamed:@"location_button.png"] forState:UIControlStateNormal];
    [locationButtonAux setBackgroundImage:[UIImage imageNamed:@"location_button.png"] forState:UIControlStateHighlighted];
    [locationButtonAux addTarget:self action:@selector(userLocation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *locationButton = [[UIBarButtonItem alloc] initWithCustomView:locationButtonAux];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"title"
                                                              style:UIBarButtonItemStyleDone
                                                             target:nil action:@selector(someMssage)];
    [locationButton setBackgroundVerticalPositionAdjustment:-20.0 forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.rightBarButtonItem = locationButton;

And I want to adjust the position of this button into the NavigationBar, because my NavigationBar is taller than normal (is customized using Appeareance).

I'm using the method setBackgroundVerticalPositionAdjustment, as you can see in the code, to do that. But is not working at all with my UIBarButtonItem, no matter what offset I put there, the button always appear close to the bottom of the bar (snapshot). BUT, if I use a normal UIBarButtonItem with a normal style (the one I called button) I DO can see how the position of the button will be altered the offset of -20. Very strange... Any ideas?

Thank you!

enter image description here


Solution

  • Perhaps something like this would work for you:

    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)]; //change this frame to counteract for your taller navbar
    [rightView addSubview:locationButtonAux];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    

    Hope this helps