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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从导航栏左右栏按钮项减少左侧空间和右侧空间相关的知识,希望对你有一定的参考价值。

我在导航栏上添加了两个自定义按钮。一个在左边,另一个在右边。我成功完成了它,

但是我没有减少按钮起点和框架之间的空间。

我尝试了很多,也给了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;

但没有帮助。

如何实现这个......?提前致谢...

这些是我喜欢的一些链接,但没有帮助太多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]

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

就这样使用。

另一答案

这是一个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)

以上是关于从导航栏左右栏按钮项减少左侧空间和右侧空间的主要内容,如果未能解决你的问题,请参考以下文章

在窗口调整大小时一一隐藏菜单项

Bootstrap 3 Navbar 左侧和右侧导航栏项目的左侧折叠菜单

如何在导航栏中将导航项对齐到右侧? [复制]

Swift 自定义导航项

iPhone:在代码中的导航栏中将“添加信息”按钮添加为右侧栏按钮项

iOS导航栏中的多个按钮通过Interface Builder?