如何在没有IB的情况下在右侧的UINavigationbar中添加2个按钮?


86

如何在UINavigationBar没有XIB的情况下添加2个按钮?
2个按钮应在的右侧对齐UINavigationBar

我知道如何添加一个按钮,但是两个按钮又如何呢?

Answers:


142

使用iOS 5+,它非常简单:

UIBarButtonItem *btnShare = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(share)];
UIBarButtonItem *btnRefresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:btnShare, btnRefresh, nil]];

我认为它也可以在iOS 5中使用。
iAmd

1
漂亮又简单!我还包括了现有的右键(在IB中设置)UIBarButtonItem * btnCurrent = self.navigationItem.rightBarButtonItem;
邓肯

43

发布了代码(请参阅下文),以在NavigationBar的右侧添加两个按钮。您可以设置barStyle = -1而不是子类化UIToolbar

UIToolbar *tools = [[UIToolbar alloc]
                    initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
tools.clearsContextBeforeDrawing = NO;
tools.clipsToBounds = NO;
tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
                                                              // anyone know how to get it perfect?
tools.barStyle = -1; // clear background
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:3];

// Create a standard refresh button.
UIBarButtonItem *bi = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh:)];
[buttons addObject:bi];
[bi release];

// Create a spacer.
bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
bi.width = 12.0f;
[buttons addObject:bi];
[bi release];

// Add profile button.
bi = [[UIBarButtonItem alloc] initWithTitle:@"Profile" style:UIBarButtonItemStylePlain target:self action:@selector(goToProfile)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];

// Add buttons to toolbar and toolbar to nav bar.
[tools setItems:buttons animated:NO];
[buttons release];
UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
[tools release];
self.navigationItem.rightBarButtonItem = twoButtons;
[twoButtons release];

这是我发现的第一篇文章,其中包含额外的工具栏设置,使其可以使用不同的背景颜色,谢谢
Chris

这是这个问题的正确答案....代码在这个环节可以正常使用...你真棒人...欢呼... :)所有其他在上面的答案是错误的,不工作
Sameera Chathuranga

当您将navigationController表示为UIPopoverController的contentViewController时,该解决方案将无法正常工作。当您将UIToolbar设置为leftBarButtonItem的自定义视图时,第二个按钮的触摸区域不正确(向左移动,这意味着第二个按钮的右侧不可单击)。当涉及rightBarButtonItem时,错误地绘制了第二个按钮(仅绘制了它的左侧)...在这种情况下,我将不得不坚持使用自定义UIToolbar作为标题而不是UINavigationBar,我认为...
manicaesar

1
这里的窍门之一是 tools.barStyle = -1:如果没有,则将UIBarStyleBlack与translucent = YES一起使用时,会出现一些视觉瑕疵。(即背景颜色与导航栏的颜色不匹配。)这是未记录的功能吗?如果是这样,则此代码是易碎的。我在文档中的任何地方都没有看到它。
埃特尔

28

您可以将使用工具栏初始化的条形按钮用作自定义视图。

UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)];
NSArray* buttons = [NSArray arrayWithObjects:self.editButtonItem, someOtherButton, nil];
[toolbar setItems:buttons animated:NO];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];

将给出这样的内容:

替代文字

注意:此答案在iOS 6或更高版本中已过时


3
@SameeraChathuranga,您不能不做任何事情就复制并粘贴此代码。您必须确保首先在某处定义了“ self.editButtonItem”和“ someOtherButton” ...
Nathan

嗨!感谢您的摘要。使用它,我成功添加了两个按钮,但是有一个小问题。是它的外观。如您所见,工具栏周围可见轻微的正方形边框。我该如何删除它并使它无缝显示,就像上面的屏幕截图一样?谢谢。:)
Isuru

很奇怪,我在“添加”按钮上没有边框。如果我使用没有图标的UIBarButtonStyles,则只会得到边框。
pojo 2013年

23

这是我当前项目中的工作示例:

两个按钮进入UINavigationbar rightBarButtonItem

UIButton *homeBtn =  [UIButton buttonWithType:UIButtonTypeCustom];
[homeBtn setImage:[UIImage imageNamed:@"home-icon"] forState:UIControlStateNormal];
//[homeBtn addTarget:self action:@selector(home) forControlEvents:UIControlEventTouchUpInside];
[homeBtn setFrame:CGRectMake(0, 0, 32, 32)];

UIButton *settingsBtn =  [UIButton buttonWithType:UIButtonTypeCustom];
[settingsBtn setImage:[UIImage imageNamed:@"settings-icon"] forState:UIControlStateNormal];
//[settingsBtn addTarget:self action:@selector(settings) forControlEvents:UIControlEventTouchUpInside];
[settingsBtn setFrame:CGRectMake(44, 0, 32, 32)];

UIView *rightBarButtonItems = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 76, 32)];
[rightBarButtonItems addSubview:homeBtn];
[rightBarButtonItems addSubview:settingsBtn];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarButtonItems];

18
UINavigationBar *navBarView = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 42.0f)];
    navBarView.tintColor= [UIColor colorWithRed:90.0/255.0f green:53.0/255.0f blue:45.0/255.0f alpha:1.0];

    UIBarButtonItem *left=[[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(backView)];
    UIBarButtonItem *right=[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(SaveImage)];
    UIBarButtonItem *Add=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(AddComment:)];

    UINavigationItem *navigationItem = [[UINavigationItem alloc] init];
    navigationItem.leftBarButtonItem = left;
    NSMutableArray *buttonArray=[[NSMutableArray alloc]initWithCapacity:2];
    [buttonArray addObject:right];
    [buttonArray addObject:Add];
    navigationItem.rightBarButtonItems = buttonArray;
    [navBarView pushNavigationItem:navigationItem animated:NO];
[self.view addSubView:navBarView];

14

迅速:

override func viewDidLoad() {
    super.viewDidLoad()

    // Additional bar button items
    let button1 = UIBarButtonItem(image: UIImage(named: "image1.png"), style: .Plain, target: self, action: "methodA")
    let button2 = UIBarButtonItem(image: UIImage(named: "image2.png"), style: .Plain, target: self, action: "methodB")
    let button3 = UIBarButtonItem(image: UIImage(named: "image3.png"), style: .Plain, target: self, action: "methodC")

    navigationItem.leftItemsSupplementBackButton = true
    navigationItem.setLeftBarButtonItem(button1, animated: true)
    navigationItem.setRightBarButtonItems([button2, button3], animated: true)

按钮的方法:

func methodA() {
    performSegueWithIdentifier("segA", sender: nil)
}

func methodB() {
    performSegueWithIdentifier("segB", sender: nil)
}

func methodC() {
    performSegueWithIdentifier("segC", sender: nil)
}

9

迅速

你可以做到迅速喜欢这个

        var editImg   : UIImage = UIImage(named: "plus")!
        var searchImg : UIImage = UIImage(named: "search")!
        
        var editBtn : UIBarButtonItem = UIBarButtonItem(image: editImg,  style: UIBarButtonItemStyle.Plain, target: self, action: Selector("editBtnPressed:"))
        
        var searchBtn : UIBarButtonItem = UIBarButtonItem(image: searchImg,  style: UIBarButtonItemStyle.Plain, target: self, action: Selector ("searchBtnPressed:"))
        
        var buttons : NSArray = [editBtn, searchBtn]
        
        self.navigationItem.rightBarButtonItems = buttons

        func editBtnPressed(sender: AnyObject){
        
        }
    
        func searchBtnPressed(sender: AnyObject){
        
        }

7

您可以创建一个UIView并在该视图中添加两个按钮。并添加该UIView作为右键:)

UIView* rightItem = [UIView alloc] initWithFrame:frame];
//Create UIButton1 b1
//Create UIButton2 b2
[rightItem addSubview:b1];
[rightItem addSubview:b2];

self.navigationItem.rightBarButtonItem = rightItem;

@NathanReed,应该是self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: rightItem];(完整的工作代码示例[由我以下])
Adnan

7

Prakash响应也可以在界面生成器中使用。

拖动UIViewUINavigationItem,那么你可以把几个UIButton作为这个孩子UIView,创造像这样一个层次结构:

具有3个按钮层次结构的导航栏

设置的背景色UIView以清除并添加一些约束以使按钮垂直居中并固定水平位置。这是零行代码的结果:

模拟器结果


1
这可行!对于那些像我一样困惑的人,我所做的就是用UIView替换Bar Button Item,而不是如上所述将其拖动到UINavigationItem。之后,它就像将按钮拖到场景并添加约束一样。这个解决方案的荣誉,因为没有任何代码,我现在可以做到这一点,而且只需拖动情节提要中的按钮就可以为不同的场景创建segue :)谢谢!
布鲁斯

2
完全不需要。您可以将条形按钮的项目拖到右条形按钮上。Xcode的7.3.1
若奥·努涅斯

4

在SWIFT中,您可以添加以下代码以在右侧(或左侧)设置两个按钮:

self.navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: "barButtonItemClicked"), UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "barButtonItemClicked")]


3

这是Swift 4代码:

    let editImage   = UIImage(named: "plus")!
    let searchImage = UIImage(named: "search")!
    let editButton   = UIBarButtonItem(image: editImage,  style: .plain, target: self, action:#selector(didTapEditButton))
    let searchButton = UIBarButtonItem(image: searchImage,  style: .plain, target: self, action:#selector(didTapSearchButton))
    navigationItem.rightBarButtonItems = [editButton, searchButton]


 @objc func didTapEditButton(sender: AnyObject){

  }

 @objc func didTapSearchButton(sender: AnyObject){

  }

2

您不必添加两个按钮。您只需要添加

UIBarButtonSystemItemFlexibleSpace 

UIBarButtonSystemItemFixedSpace

和一个按钮,使其位于右侧。

像这样:

UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
toolbar.barStyle = UIBarStyleBlackTranslucent;

UIBarButtonItem *spaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

UIBarButtonItem *infoButtonItem1 = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(empresaTextFieldDone)];    

toolbar.items = [NSArray arrayWithObjects: spaceButton, infoButtonItem1, nil];   

2
UIView* buttonsView= [[UIView alloc] initWithFrame:CGRectMake(10, 6, 84, 32)];
buttonsView.backgroundColor=[UIColor clearColor];

btn_back = [UIButton buttonWithType:UIButtonTypeCustom];
[btn_back addTarget:self action:@selector(backButtonClick) 
forControlEvents:UIControlEventTouchUpInside];
btn_back.frame = CGRectMake(0, 0, 32, 32);
btn_back.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"close.png"]];

btn_help = [UIButton buttonWithType:UIButtonTypeCustom];
[btn_help addTarget:self action:@selector(helpButtonClick) 
 forControlEvents:UIControlEventTouchUpInside];
btn_help.frame = CGRectMake(42, 0, 32, 32);
btn_help.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"info.png"]];

[buttonsView addSubview:btn_back];
[buttonsView addSubview:btn_help];

segmentItem = [[UIBarButtonItem alloc] initWithCustomView:buttonsView];
self.navigationItem.rightBarButtonItem = segmentItem;

1

如果有人像我一样来到这里,寻找MonoTouch的答案,那就别无选择了NavigationItem.RightBarButtonItems


1

在SWIFT中:

(假设您有一个导航控制器)在根控制器中,请使用以下代码:

剩下: ..

    let leftBtn =  UIBarButtonItem(title: "Do It", style: UIBarButtonItemStyle.Plain,
        target: self, action: "doIt:")
    leftBtn.tag=100
    self.navigationItem.leftBarButtonItem = leftBtn

对:

    let rightView = UIView(frame:  CGRectMake(0, 0, 100, 30))
    rightView.backgroundColor = UIColor.redColor()

    let btn1 = UIButton(frame: CGRectMake(0,0,60, 20))
    btn1.setTitle("R1", forState: UIControlState.Normal)
    btn1.tag=101
    btn1.addTarget(self, action: "doIt:", forControlEvents: UIControlEvents.TouchUpInside)
    rightView.addSubview(btn1)

    let btn2 = UIButton(frame: CGRectMake(30,0,60, 20))
    btn2.setTitle("R2", forState: UIControlState.Normal)
    btn2.tag=102
    btn2.addTarget(self, action: "doIt:", forControlEvents: UIControlEvents.TouchUpInside)
    rightView.addSubview(btn2)


    let rightBtn = UIBarButtonItem(customView: rightView)
    self.navigationItem.rightBarButtonItem = rightBtn;

..

哪里:

 func doIt(sender: AnyObject!){
    let tag = sender.tag

}

0
    func makeCustomNavigationBar () {

        // Create the navigation bar
        let navigationBar = UINavigationBar(frame: CGRectMake(0, 20, self.view.frame.size.width, 44)) // Offset by 20 pixels vertically to take the status bar into account
        navigationBar.backgroundColor = UIColor.init(hexString: "E43037")
        navigationBar.delegate = self;

        navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
        navigationBar.shadowImage = UIImage()
        navigationBar.translucent = true

        // Create a navigation item with a title
        let navigationItem = UINavigationItem()
        navigationBar.tintColor = UIColor.whiteColor()

        navigationItem.title = "Forgot Password"
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

        // Create left and right button for navigation item
        let leftButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
        leftButton.action = "returnToLoginView"

        let backbuttonImageView =  UIImageView(frame: CGRectMake(0, 0, 30, 30))
        backbuttonImageView.image = UIImage(named: "nav-arrow-left")
        leftButton.image = backbuttonImageView.image
        navigationItem.leftBarButtonItem = leftButton


let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
        rightButton.action = "navigateToDashBoardView"

        let rightButtonImageView =  UIImageView(frame: CGRectMake(0, 0, 30, 30))
        rightButtonImageView.image = UIImage(named: "nav-arrow-left")
        rightButton.image = backbuttonImageView.image
        navigationItem.rightBarButtonItem = rightButton

        // Assign the navigation item to the navigation bar
        navigationBar.items = [navigationItem]

        // Make the navigation bar a subview of the current view controller
        self.view.addSubview(navigationBar)
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.