【问题标题】:reduce left space and right space from navigation bar left and right bar button item从导航栏左右栏按钮项减少左右空间
【发布时间】:2015-01-30 09:24:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios xcode navigationbar


    【解决方案1】:
    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。现在它工作正常谢谢
    • 对于 iphone 6 和 6 plus 你必须使用不同的空间。
    • @Yusufterzi,对我来说,我想在左栏按钮(后退按钮)上添加空间。我怎样才能做到这一点?
    • 我需要 swift 4 版本
    【解决方案2】:

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

    【讨论】: