问题
I am adding two custom buttons on navigation bar. one at left and other at right. I am successfully done with it,
but I failed to reduce the space between the starting point and frame of buttons.
I tried a lot, also gave the negative value of x, still didn't helped. Here is the code for 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 to achieve this...? Thanks in advance...
These are the some links that I preferred but didn't helped 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]
回答1:
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.
回答2:
Here's a Swift version:
let negativeSpacer = UIBarButtonItem()
negativeSpacer.width = -16
let hamburgerButton = UIBarButtonItem(image: UIImage(named: "hamburgerMenu")?.withRenderingMode(.alwaysOriginal),
style: .plain,
target: self,
action: #selector(menuButtonPressed))
navigationItem.setLeftBarButtonItems([negativeSpacer, hamburgerButton], animated: true)
来源:https://stackoverflow.com/questions/27244204/reduce-left-space-and-right-space-from-navigation-bar-left-and-right-bar-button