减少导航栏左右按钮项的左侧和右侧空间

3
我正在导航栏上添加两个自定义按钮,一个在左边,另一个在右边。我已经成功完成了它,但是我没有减少起始点和按钮框架之间的空间。
我尝试了很多次,也给出了负值的x,但仍然没有帮助。以下是按钮的代码:
-(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];
}

也尝试使用了

aBarButtonItem.width = -16;

但并没有帮助。

如何实现这个呢...? 提前感谢...

这些是我喜欢的一些链接,但并没有什么帮助 如何编辑UINavigationBar中左右UIBarButtonItem的空白间隙 [iOS 7]

如何编辑UINavigationBar中左右UIBarButtonItem的空白间隙 [iOS 7]

输入图片说明

2个回答

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

像这样使用。


嗨Yusuf,谢谢。它起作用了,之前我是直接在setLeftBarButtonItems上添加UIButton。 现在它正常工作了,谢谢。 - Sagar
对于 iPhone 6 和 6 Plus,您必须使用不同的空间。 - Yusuf terzi
1
@Yusufterzi,对我来说,我想在左侧的导航栏按钮(返回按钮)上添加空格。我该如何实现这一点? - May Phyu
我需要Swift 4版本。 - Benny Wijaya

1
这是一个Swift版本:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接