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

Posted

技术标签:

【中文标题】如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar?【英文标题】:How to add 2 buttons into the UINavigationbar on the right side without IB? 【发布时间】:2010-12-20 16:33:34 【问题描述】:

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

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

【问题讨论】:

【参考方案1】:

使用 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 中也可用。 又好又简单!我还包括了现有的右键(在 IB 中设置) UIBarButtonItem *btnCurrent = self.navigationItem.rightBarButtonItem;【参考方案2】:

我posted code(见下文)在导航栏的右侧添加了两个按钮。您可以设置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];

【讨论】:

这是我发现的第一篇文章,其中包含额外的工具栏设置,使其适用于不同的背景颜色,谢谢 这是这个问题的正确答案....此链接中的代码运行良好...你真棒人...干杯... :) 上面的所有其他答案都是错误的并且不工作 当您将navigationController 呈现为UIPopoverController 的contentViewController 时,该解决方案无法完美运行。当您将UIToolbar设置为leftBarButtonItem的自定义视图时,第二个按钮的触摸区域不正确(向左移动,即第二个按钮的右侧不可点击)。当涉及到 rightBarButtonItem 时,第二个按钮被错误地绘制(只绘制了左侧)......在这种情况下,我将不得不坚持使用自定义 UIToolbar 作为标题而不是 UINavigationBar 我认为...... 这里的技巧之一是tools.barStyle = -1 行:如果您使用带有translucent=YES 的UIBarStyleBlack,则会出现一些视觉伪影。 (即背景颜色与导航栏的颜色不匹配。)这是未记录的功能吗?如果是这样,这段代码有点脆弱。我在文档中的任何地方都没有看到。【参考方案3】:

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

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 或更高版本已过时

【讨论】:

@SameeraChathuranga 你不能只复制和粘贴这段代码而不做任何事情。您必须确保首先在某处定义了“self.editButtonItem”和“someOtherButton”... 嗨!谢谢sn-p。使用它我成功添加了两个按钮,但有一个小问题。 Here 的样子。如您所见,工具栏周围有一个轻微的方形边框。我怎样才能删除它并让它像你在上面的屏幕截图中一样无缝?谢谢。 :) 奇怪,我没有得到“添加”按钮的边框。如果我使用没有图标的 UIBarButtonStyles,我只会得到一个边框。【参考方案4】:

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

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];

【讨论】:

【参考方案5】:
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];

【讨论】:

【参考方案6】:

斯威夫特:

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)

【讨论】:

【参考方案7】:

斯威夫特

你可以在 swift 中这样做

        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)
        
        

【讨论】:

【参考方案8】:

您可以创建一个 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];(下面的完整工作代码示例 [by me])【参考方案9】:

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

UINavigationItem 中拖一个UIView,然后你可以把几个UIButton 作为这个UIView 的孩子,然后创建一个像这样的层次结构:

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

【讨论】:

这行得通!对于那些和我一样困惑的人,我所做的是将 Bar Button Item 替换为 UIView,而不是按照描述将其拖动到 UINavigationItem。之后,它将与将按钮拖动到场景并添加约束完全相同。这个解决方案的荣誉,因为没有任何代码我现在可以做到这一点,只需拖动故事板中的按钮即可创建不同场景的 segue :) 谢谢! 这根本不需要。您只需将 bar button 项拖动到右侧 bar button 即可。 Xcode 7.3.1【参考方案10】:

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

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

【讨论】:

【参考方案11】:

从 iOS 5 开始,很容易实现。 UINavigationItem 能够在栏的左侧和右侧拥有多个按钮。

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UINavigationItem_Class/Reference/UINavigationItem.html#//apple_ref/occ/instm/UINavigationItem/setRightBarButtonItems:animated:

【讨论】:

【参考方案12】:

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

  

【讨论】:

【参考方案13】:

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

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];   

【讨论】:

【参考方案14】:
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;

【讨论】:

【参考方案15】:

如果有人像我一样来到这里寻找 MonoTouch 的答案,只需查看 NavigationItem.RightBarButtonItems 数组即可。

【讨论】:

【参考方案16】:

在 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


【讨论】:

【参考方案17】:
    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)
    

【讨论】:

以上是关于如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar?的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有 usermod 的情况下将用户添加到组?

如何在没有列表定义的情况下将列表列添加到列表实例

如何在不创建嵌套数组的情况下将多个变量添加到数组

ios:如何在没有连接设备的情况下将新的 UDID 添加到配置文件?

如何在没有 Webpacker 的情况下将 Tailwind CSS 添加到 Rails?

如何在不破坏滚动功能的情况下将 UIImage 添加到 UIScrollView?