Search code examples
iosxcodenavigationbar

reduce left space and right space from navigation bar left and right bar button item


I am adding two custom buttons on the navigation bar, one on the left and another on the right. I have done it successfully but I failed to reduce the space between the starting point and the frame of buttons.

I tried a lot, also gave the negative value of x, but it still didn't help. Here is the code for the buttons:

-(void)addLeftButton
{
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aButton.backgroundColor = [UIColor redColor];
    [aButton setTitle:@"H" forState:UIControlStateNormal];
    aButton.frame = CGRectMake(0.0, 0.0, 40, 40);
    [aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
    [aButton addTarget:self action:@selector(backBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setLeftBarButtonItem:aBarButtonItem];
}

-(void)addRightButton
{
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aButton.backgroundColor = [UIColor greenColor];
    [aButton setTitle:@"B" forState:UIControlStateNormal];
    aButton.frame = CGRectMake(0.0, 0.0, 40, 40);
    [aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
    [aButton addTarget:self action:@selector(backBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:aBarButtonItem];
}

Also tried using:

aBarButtonItem.width = -16;

but didn't helped.

How do I achieve this?

These are the some links that I preferred but didn't help much How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]

How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]

enter image description here


Solution

  • UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                                               initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                               target:nil action:nil];
        negativeSpacer.width = -16;
        [self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,yourbutton, nil] animated:YES];
    

    Use like that.