Come aggiungere 2 pulsanti nella barra di navigazione UIN sul lato destro senza IB?


86

Come posso aggiungere 2 pulsanti in UINavigationBarsenza XIB?
I 2 pulsanti dovrebbero essere allineati sul lato destro del UINavigationBar.

So come posso aggiungere un pulsante, ma che ne dici di due?

Risposte:


142

Con iOS 5+ è facile come:

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

Penso che sia disponibile anche in iOS 5.
— iAmd

1
Bello e semplice! Ho anche incluso il pulsante destro esistente (impostato in IB) UIBarButtonItem * btnCurrent = self.navigationItem.rightBarButtonItem;
— Duncan

43

Ho pubblicato il codice (vedi sotto) per aggiungere due pulsanti a destra della barra di navigazione. Puoi impostare barStyle = -1invece di sottoclassare 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];

questo è stato il primo post che ho scoperto che includeva una configurazione aggiuntiva della barra degli strumenti che la fa funzionare con diversi colori di sfondo, grazie
— Chris

Questa è la risposta corretta per questa domanda .... Il codice in questo link funziona perfettamente ... tu uomo fantastico ... ciao ... :) Tutte le altre risposte sopra sono sbagliate e non funzionano
— Sameera Chathuranga

La soluzione non funziona perfettamente, quando presenti il ​​navigationController come contentViewController di UIPopoverController. Quando si imposta UIToolbar come visualizzazione personalizzata di leftBarButtonItem, l'area di tocco del secondo pulsante non è corretta (spostata a sinistra, il che significa che il lato destro del secondo pulsante non è selezionabile). Quando si tratta di rightBarButtonItem, il secondo pulsante è disegnato in modo errato (solo il lato sinistro è disegnato) ... In questo caso dovrò attenermi all'uso di UIToolbar personalizzata come intestazione invece di UINavigationBar penso ...
— manicaesar

1
Uno dei trucchi qui è la tools.barStyle = -1linea: senza di essa ci sono alcuni artefatti visivi se usi UIBarStyleBlack con translucent = YES. (Vale a dire il colore di sfondo non corrisponde a quello della barra di navigazione.) È una caratteristica non documentata? Se è così, questo codice è piuttosto fragile. Non l'ho visto da nessuna parte nei documenti.
— ettore

28

È possibile utilizzare un pulsante della barra inizializzato con una barra degli strumenti come visualizzazione personalizzata.

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

Darebbe qualcosa del genere:

testo alternativo

Nota: questa risposta è obsoleta per iOS 6 o versioni successive


3
@SameeraChathuranga non puoi semplicemente copiare e incollare questo codice senza fare nulla. Devi assicurarti che 'self.editButtonItem' e 'someOtherButton' siano definiti da qualche parte prima ...
— Nathan

Ciao! Grazie per lo snippet. Usandolo ho aggiunto due pulsanti con successo ma c'è un piccolo problema. Ecco come appare. Come puoi vedere, intorno alla barra degli strumenti è visibile un leggero bordo quadrato. Come posso rimuoverlo e renderlo trasparente come se fosse nel tuo screenshot qui sopra? Grazie. :)
— Isuru

Strano, non vedo il bordo sul pulsante "aggiungi". Ottengo un bordo solo se utilizzo UIBarButtonStyles che non hanno un'icona.
— pojo

23

Ecco l'esempio funzionante del mio progetto attuale:

due pulsanti nella barra di navigazione UIN 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

Swift:

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)

Metodi per i pulsanti:

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

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

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

9

SWIFT

Puoi farlo rapidamente in questo modo

        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

È possibile creare una vista UIV e aggiungere due pulsanti in quella vista. E aggiungi quell'UIView come pulsante destro :)

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

self.navigationItem.rightBarButtonItem = rightItem;

@NathanReed, dovrebbe essere self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: rightItem];(Esempio di codice funzionante completo di seguito [da me])
— Adnan

7

La risposta di Prakash funziona anche nel generatore di interfacce.

Trascina un UIViewin UINavigationItem, quindi puoi metterne diversi UIButtoncome figli di questo UIViewe creare una gerarchia in questo modo:

Barra di navigazione con 3 pulsanti gerarchici

Imposta il colore di sfondo UIViewper chiaro e aggiungi alcuni vincoli per centrare verticalmente i pulsanti e fissare la posizione orizzontale. Ecco il risultato che ho ottenuto con zero righe di codice:

Risultato nel simulatore


1
Funziona! Per coloro che sono confusi come me, quello che ho fatto è stato sostituire l'elemento del pulsante a barre con l'UIView invece trascinandolo nell'UINavigationItem come descritto. Dopodiché sarà esattamente lo stesso come trascinare i pulsanti sulla scena e aggiungere vincoli. Complimenti per questa soluzione perché senza alcun codice ora posso farlo oltre a creare sequenze diverse semplicemente trascinando i pulsanti nello storyboard :) Grazie!
— Bruce

2
Questo non è affatto necessario. Puoi semplicemente trascinare gli elementi del pulsante della barra sul pulsante della barra di destra. Xcode 7.3.1
— João Nunes

4

In SWIFT, puoi aggiungere questo codice per impostare due pulsanti sul lato destro (o sinistro):

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


3

Ecco il codice 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

Non è necessario aggiungere due pulsanti. Devi solo aggiungere

UIBarButtonSystemItemFlexibleSpace 

non

UIBarButtonSystemItemFixedSpace

e un pulsante, in modo che sia sul lato destro.

Come questo:

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

Nel caso in cui qualcuno venga qui, come me, alla ricerca di una risposta MonoTouch, non cercare oltre NavigationItem.RightBarButtonItemsarray.


1

in SWIFT:

(supponiamo tu abbia un controller di navigazione) in Root Controller usa questo codice:

sinistra: ..

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

giusto:

    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;

..

dove:

 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)
    }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.