Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove padding next to a UIBarButtonItem

I have added a custom button to the navigation bar's custom right bar button item as shown in the image.

I'm want to be able to remove the space after the button so that it touches the right edge of the screen but couldn't find a solution even after searching. If someone could mention how, would be great.

This is the code I'm using

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
aButton.frame = CGRectMake(50.0, 0.0, 60, 44);
UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
[aButton addTarget:self action:@selector(testButtonControl:) forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.rightBarButtonItem = aBarButtonItem;

enter image description here

like image 396
carbonr Avatar asked Aug 05 '12 08:08

carbonr


2 Answers

You can add a fixed space element with a negative width (I know, this sounds like a hack, but it works):

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
aButton.frame = CGRectMake(50.0, 0.0, 60, 44);
UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
[aButton addTarget:self action:@selector(testButtonControl:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *spaceFix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];
spaceFix.width = -5;

self.navigationItem.rightBarButtonItems = @[spaceFix, aBarButtonItem];
like image 188
Tom Avatar answered Sep 27 '22 16:09

Tom


You have to create a new view, add button and everything else you want and add it to the titleView as shown.

- (void)viewDidLoad {
    self.navigationItem.titleView = [self titleView];
}

- (UIView *)titleView {
    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
    CGFloat width = 0.95 * self.view.frame.size.width;
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, navBarHeight)];
..
// please add what you need here
....
}
like image 25
carbonr Avatar answered Sep 27 '22 17:09

carbonr