Añadir botón a la barra de navegación mediante programación


Hola Necesito configurar el botón en el lado derecho, en la barra de navegación, programáticamente , de modo que si presiono el botón realizaré algunas acciones. He creado la barra de navegación, programáticamente por;

navBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0,0,320,44) ];

Del mismo modo, necesito agregar el botón, en el lado derecho de esta barra de navegación. Para eso usé,

1.  

    UIView* container = [[UIView alloc] init];

    // create a button and add it to the container
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 130, 44.01)];
    [container addSubview:button];
    [button release];

    // add another button
    button = [[UIButton alloc] initWithFrame:CGRectMake(160, 0, 50, 44.01)];
    [container addSubview:button];
    [button release];

    // now create a Bar button item
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:container];

    // set the nav bar's right button item
    self.navigationItem.rightBarButtonItem = item;
    [item release];

2.  

    UIImage *im;
    im=[UIImage imageNamed:@"back.png"];
    [button setImage:im forState:UIControlStateNormal];
    [im release];
    backButton = [[UIBarButtonItem alloc] initWithCustomView:button];       
    [backButton setImageInsets:UIEdgeInsetsMake(0, -10,5, 5)];
    [self.navigationItem setRightBarButtonItem:backButton];

3.  

    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithTitle:@"button"               style:UIBarButtonItemStylePlain target:self action:@selector(refreshLogsAction:)];
    self.navigationItem.rightBarButtonItem = refreshItem;

    [refreshItem release];

Probé todas estas formas, pero ninguna muestra el botón en el lado derecho.

Author: Bhavin Ramani, 2010-05-17

12 answers

Dentro de mi clase derivada UIViewController, estoy usando lo siguiente dentro de viewDidLoad:

UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Flip"                                            
                               style:UIBarButtonItemStyleBordered 
                               target:self 
                               action:@selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];

Esto agrega un botón a la derecha con el volteo de título, que llama al método:

-(IBAction)flipView

Esto se parece mucho a ti #3, pero está funcionando dentro de mi código.

 179
Author: Xetius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-28 05:27:25
UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);

UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
     forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];

UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];

///// evento llamado

-(IBAction)Back_btn:(id)sender
{
    //Your code here
}

SWIFT:

var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)

var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true

var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton

func back_btn(_ sender: Any) {
    //Your code here
}
 19
Author: Bhavesh Nayi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 13:41:10

Para agregar el botón de búsqueda en la barra de navegación use este código:

 UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;

Y aplicar el siguiente método:

- (IBAction)toggleSearch:(id)sender
{
    // do something or handle Search Button Action.
}
 9
Author: Muhammad Jabbar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 06:28:01

Cómo agregar un botón agregar a la barra de navegación en swift:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onAdd:")

OnAdd:

func onAdd(sender: AnyObject) {
}
 6
Author: raf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-07 15:48:15

Versión Swift, agregue esto en viewDidLoad:

var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneButton:")
navigationItem.rightBarButtonItem = doneButton

Y esto en su clase de Controlador de vista

func doneButton(sender: UIBarButtonItem) {
    println(111)
}
 5
Author: Esqarrouth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-28 15:32:19
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];

-(void)saveAction:(UIBarButtonItem *)sender{

//perform your action

}
 5
Author: Gurpreet Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-24 05:55:47

En el método viewDidLoad de ViewController.m

UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];

[self.navigationItem setLeftBarButtonItem:cancel];

"(back) " selector es un método para dismiss el ViewController actual

 3
Author: iAnkit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-08 07:11:48

Utilice el siguiente código:

UIBarButtonItem *customBtn=[[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStylePlain target:self action:@selector(customBtnPressed)];
[self.navigationItem setRightBarButtonItem:customBtn];
 3
Author: Himanshu Mahajan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-28 05:27:50

Simple use editBarButton nativo como este

self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.navigationItem.rightBarButtonItem setAction:@selector(editBarBtnPressed)];

Y luego

- (void)editBarBtnPressed {
    if ([infoTable isEditing]) {
        [self.editButtonItem setTitle:@"Edit"];
        [infoTable setEditing:NO animated:YES];
    }
    else {
        [self.editButtonItem setTitle:@"Done"];
        [infoTable setEditing:YES animated:YES];
    }
}

Diviértete...!!!

 2
Author: Salman Iftikhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-01 06:30:35

Intente this.It trabaja para mí. Agregar botón a la barra de navegación mediante programación, También configuramos la imagen en el botón de la barra de navegación,

A continuación se muestra el código: -

  UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:
  [[UIImage imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] 
  style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
  self.navigationItem.rightBarButtonItem=Savebtn;

  -(void)SaveButtonClicked
  {
    // Add save button code.
  }
 2
Author: Jaywant Khedkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 06:49:02

Si no está buscando un barButtonItem sino un botón simple en la barra de navegación, el siguiente código funciona:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:@"NavBar.png"] forState:UIControlStateNormal];
[aButton addTarget:self
            action:@selector(showButtonView:)
  forControlEvents:UIControlEventTouchUpInside];
aButton.frame = CGRectMake(260.0, 10.0, 30.0, 30.0);
[self.navigationController.navigationBar addSubview:aButton];
 0
Author: iking,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-30 21:56:01

Hola a todos !! Creé la solución al problema en cuestión donde se quieren dos orientaciones UIInterface utilizando el UIImagePicker.. En mi ViewController donde manejo el segue al UIImagePickerController

* * Uso a..

-(void) editButtonPressed:(id)sender {
   BOOL editPressed = YES;
    NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
    [boolDefaults setBool:editPressed forKey:@"boolKey"];
    [boolDefaults synchronize];

    [self performSegueWithIdentifier:@"photoSegue" sender:nil]; 

}

**

Luego en la clase AppDelegate hago lo siguiente.

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    BOOL appDelBool;
    NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
    appDelBool = [boolDefaults boolForKey:@"boolKey"];

       if (appDelBool == YES)
           return (UIInterfaceOrientationMaskPortrait);
        else
            return UIInterfaceOrientationMaskLandscapeLeft;
}
 -1
Author: John Z,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-17 19:29:26