Objective-c – How to adjust UIToolBar left and right padding

iphoneobjective c

I create one UIToolbar with code and another with interface builder. But, found out the two toolbar having different left and right padding which shown below:

From Interface Builder:

enter image description here

From Code:

enter image description here

UIImage *buttonImage = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTest setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnTest setTitle:@"Back" forState:UIControlStateNormal];   
[btnTest.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];  
[btnTest setBackgroundImage:[imgToolbarButton stretchableImageWithLeftCapWidth:5 topCapHeight:0]  forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(clearDateEdit:) forControlEvents:UIControlEventTouchUpInside];
btnTest.frame = CGRectMake(0.0, 0.0, 50, 30);
UIBarButtonItem *btnTestItem = [[UIBarButtonItem alloc] initWithCustomView:btnTest];
[self.toolbar setItems:[NSArray arrayWithObjects:btnTestItem,nil]];
[btnTestItem release];

My question is how can I adjust the left and right padding of UIToolbar by code?

Update

I discovered this alignment issue only happen to UIBarButtonItem with customView of UIButton, the alignment is fine with UIBarButtonItem. Any idea what cause this or to resolve this.

The only solution I can think of right now is to manually set the frame.

Best Answer

I had the same issue, and there's a neat trick you can do with a UIBarButtonSystemItemFixedSpace, add one of these with a negative width before your first button and after your last button and it will move the button to the edge.

For example, to get rid of the right hand margin add the following FixedSpace bar item as the last item:

Update for iOS 11 up to 13

  • Swift

    let negativeSeperator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
    negativeSeperator.width = 12
    

    Width must be positive in Swift version


  • Objc

    UIBarButtonItem *negativeSeparator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSeparator.width = -12;
    

The margins on the left and right are 12px.

Update for iOS7 - margins are 16px on iPhone and 20px on iPad!

Related Topic