Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UINavigationBar - change UIBarButtonItem positions

I am using a UINavigationController and its bar within my app. Now I want to change the leftBarButtonItem and rightBarButtonItem positions. I want them to be on a different x and y position having a custom witdth and height.

But the problem is, that changing the frame does not change anything with the barButtonItem. I do not now why, but the frame always gets resetted to its original coordinates.

Here is my code which I call in viewWillAppear:

UINavigationItem *navItem = [[self.navigationBar items] lastObject];

UIView *rightview = [[UIView alloc] initWithFrame:CGRectMake(0,0,66,30)];
rightview.backgroundColor = [UIColor blueColor];

//add custom view
UIBarButtonItem *search = [[UIBarButtonItem alloc] initWithCustomView:rightview];
navItem.leftBarButtonItem = search;

And here is the result

The view is not starting at 0/0, the x position for example is at 5px insetead of 0.

Any suggestions on how to solve this issue?

like image 789
Alexander Avatar asked Dec 06 '22 12:12

Alexander


1 Answers

This worked for me for the leftBarButtonItem: If you want the UIBarButtonItem to show exactly at position (0, 0), you can create a UIButton, sets its frame to (-5, 0, width, height), assuming that the offet of a left barbutton item is (5, 0), and place that in a UIView that you set as leftBarButtonItem.

#import "UINavigationItem+CSAButtons.h"

@implementation UINavigationItem (CSAButtons)


- (void) makeLeftBarButtonWithTarget:(id)target action:(SEL)action {

    UIImage * imageNormal = [UIImage imageNamed:@"normal.png"]; 
    UIImage * imageHighlighted = [UIImage imageNamed:@"highlighted.png"]; 
    UIImage * imageDisabled = [UIImage imageNamed:@"disabled.png"]; 

    // create your button
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.exclusiveTouch = YES;
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:imageNormal forState:UIControlStateNormal];
    [button setBackgroundImage:imageHighlighted forState:UIControlStateHighlighted];
    [button setBackgroundImage:imageDisabled forState:UIControlStateDisabled];

    // set the frame of the button (better to grab actual offset of leftbarbuttonitem instead of magic numbers)
    button.frame = CGRectMake(-5.0, 0.0, imageNormal.size.width, imageNormal.size.height);
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, imageNormal.size.width, imageNormal.size.height)];
    [view addSubview:button];

    // set the barbuttonitem to be the view
    UIBarButtonItem * barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.leftBarButtonItem = barButtonItem;
}
like image 75
Aurelien Cobb Avatar answered Dec 28 '22 04:12

Aurelien Cobb