Pregunta

Estoy intentando agregar un botón de actualización a la barra superior de un controlador de navegación sin éxito.

Aquí está el encabezado:

@interface PropertyViewController : UINavigationController {

}

Así es como estoy tratando de agregarlo:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain
                                          target:self action:@selector(refreshPropertyList:)];      
        self.navigationItem.rightBarButtonItem = anotherButton;
    }
    return self;
}
¿Fue útil?

Solución

Intenta hacerlo en viewDidLoad. Por lo general, debe diferir todo lo que pueda hasta ese punto de todos modos, cuando se inicia un UIViewController, aún puede pasar bastante tiempo antes de que se muestre, no tiene sentido hacer el trabajo temprano y bloquear la memoria.

- (void)viewDidLoad {
  [super viewDidLoad];

  UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(refreshPropertyList:)];          
  self.navigationItem.rightBarButtonItem = anotherButton;
  // exclude the following in ARC projects...
  [anotherButton release];
}

En cuanto a por qué no funciona actualmente, no puedo decir con 100% de certeza sin ver más código, pero suceden muchas cosas entre init y la carga de la vista, y puede estar haciendo algo que causa la navegación para restablecer en el medio.

Otros consejos

Intente agregar el botón al elemento de navegación del controlador de vista que se va a insertar en esta clase PropertyViewController que ha creado.

Eso es:

MainViewController *vc = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
vc.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];

PropertyViewController *navController = [[PropertyViewController alloc] initWithRootViewController:vc];

Ahora, este infoButton que se ha creado programáticamente aparecerá en la barra de navegación. La idea es que el controlador de navegación recoja su información de visualización (título, botones, etc.) del UIViewController que está a punto de mostrar. En realidad no agrega botones y tal directamente al UINavigationController .

Parece que algunas personas (como yo) pueden venir aquí buscando cómo agregar un botón de barra de navegación en el Creador de interfaces. La respuesta a continuación muestra cómo hacerlo.

Agregue un controlador de navegación a su guión gráfico

Seleccione su controlador de vista y luego en el menú Xcode elija Editor > Incrustar en > Controlador de navegación .

 ingrese la descripción de la imagen aquí

Como alternativa, puede agregar un UINavigationBar desde la Biblioteca de objetos.

Agregar un elemento de botón de barra

Arrastre un UIBarButtonItem desde la Biblioteca de objetos a la barra de navegación superior.

 ingrese la descripción de la imagen aquí

Debería verse así:

 ingrese la descripción de la imagen aquí

Establecer los atributos

Puede hacer doble clic en " Elemento " para cambiar el texto a algo así como "Actualizar", pero hay un icono real para Actualizar que puede usar. Simplemente seleccione el Inspector de atributos para el UIBarButtonItem y para Elemento del sistema elija Actualizar .

 ingrese la descripción de la imagen aquí

Eso le dará el icono de actualización predeterminado.

 ingrese la descripción de la imagen aquí

Agregar una acción IB

Controle el arrastre desde el UIBarButtonItem al controlador de vista para agregar un @IBAction .

class ViewController: UIViewController {

    @IBAction func refreshBarButtonItemTap(sender: UIBarButtonItem) {

        print("How refreshing!")
    }

}

Eso es todo.

Hay un botón de sistema predeterminado para "Actualizar":

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] 
                            initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                            target:self action:@selector(refreshClicked:)] autorelease];
    self.navigationItem.rightBarButtonItem = refreshButton;

}

- (IBAction)refreshClicked:(id)sender {

}

Puedes usar esto:

Objetivo-C

UIBarButtonItem *rightSideOptionButton = [[UIBarButtonItem alloc] initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:@selector(rightSideOptionButtonClicked:)];          
self.navigationItem.rightBarButtonItem = rightSideOptionButton;

Swift

let rightSideOptionButton = UIBarButtonItem()
rightSideOptionButton.title = "Right"
self.navigationItem.rightBarButtonItem = rightSideOptionButton
-(void) viewWillAppear:(BOOL)animated
{

    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRight setFrame:CGRectMake(0, 0, 30, 44)];
    [btnRight setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [btnRight addTarget:self action:@selector(saveData) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtnRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    [barBtnRight setTintColor:[UIColor whiteColor]];
    [[[self tabBarController] navigationItem] setRightBarButtonItem:barBtnRight];

}

Para Swift 2:

self.title = "Your Title"

var homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))

var logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))

self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton

Aquí está la solución en Swift (configure las opciones según sea necesario):

var optionButton = UIBarButtonItem()
optionButton.title = "Settings"
//optionButton.action = something (put your action here)
self.navigationItem.rightBarButtonItem = optionButton

¿Por qué son subclases UINavigationController ? No hay necesidad de subclasificarlo si todo lo que necesita hacer es agregarle un botón.

Configure una jerarquía con un UINavigationController en la parte superior, y luego en el método viewDidLoad: de su controlador de vista raíz: configure el botón y adjúntelo al elemento de navegación llamando

[[self navigationItem] setRightBarButtonItem:myBarButtonItem];

Puedes probar

self.navigationBar.topItem.rightBarButtonItem = anotherButton;

Swift 4:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "tap me", style: .plain, target: self, action: #selector(onButtonTap))
}

@objc func onButtonTap() {
    print("you tapped me !?")
}
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];
view.backgroundColor = [UIColor clearColor];

UIButton *settingsButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[settingsButton setImage:[UIImage imageNamed:@"settings_icon_png.png"] forState:UIControlStateNormal];
[settingsButton addTarget:self action:@selector(logOutClicked) forControlEvents:UIControlEventTouchUpInside];
[settingsButton setFrame:CGRectMake(40,5,32,32)];
[view addSubview:settingsButton];

UIButton *filterButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[filterButton setImage:[UIImage imageNamed:@"filter.png"] forState:UIControlStateNormal];
[filterButton addTarget:self action:@selector(openActionSheet) forControlEvents:UIControlEventTouchUpInside];
[filterButton setFrame:CGRectMake(80,5,32,32)];
[view addSubview:filterButton];



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

Prueba esto. Funciona para mí.

Barra de navegación y también agregó imagen de fondo al botón derecho.

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

Use este código para la barra de navegación del botón derecho con su título ganado y llame a un método después de hacer clic con el botón derecho.

UIBarButtonItem *btnSort=[[UIBarButtonItem alloc]initWithTitle:@"right" style:UIBarButtonItemStylePlain target:self action:@selector(sortedDataCalled)];
   self.navigationItem.rightBarButtonItem=btnSort;
}

-(void)sortedDataCalled {
    NSLog(@"callBtn");    
}
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
self.navigationItem.rightBarButtonItem = rightBarButtonItem;
- (void)viewWillAppear:(BOOL)animated
{    
    [self setDetailViewNavigationBar];    
}
-(void)setDetailViewNavigationBar
{
    self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
    [self setNavigationBarRightButton];
    [self setNavigationBarBackButton];    
}
-(void)setNavigationBarBackButton// using custom button 
{
   UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"  Back " style:UIBarButtonItemStylePlain target:self action:@selector(onClickLeftButton:)];          
   self.navigationItem.leftBarButtonItem = leftButton;    
}
- (void)onClickLeftButton:(id)sender 
{
   NSLog(@"onClickLeftButton");        
}
-(void)setNavigationBarRightButton
{

  UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(onClickrighttButton:)];          
self.navigationItem.rightBarButtonItem = anotherButton;   

}
- (void)onClickrighttButton:(id)sender 
{
   NSLog(@"onClickrighttButton");  
}
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshData)];



}

-(void)refreshData{
    progressHud= [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    [progressHud setLabelText:@"拼命加载中..."];
    [self loadNetwork];
}

Debe agregar su elemento BarButtonItem en - (void) pushViewController: (UIViewController *) viewController animated: (BOOL) animated .

Simplemente copie y pegue este código Objective-C.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
    UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [btnAddContact addTarget:self action:@selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
    self.navigationItem.rightBarButtonItem = barButton;
}

#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}

Este problema puede ocurrir si eliminamos el controlador de vista o intentamos agregar un nuevo controlador de vista dentro del generador de interfaz (main.storyboard). Para solucionar este problema, se requiere agregar " Elemento de navegación " dentro del nuevo controlador de vista. A veces sucede que creamos una nueva pantalla de controlador de vista y no se conecta al " Elemento de navegación " automáticamente.

  1. Vaya al main.storyboard.
  2. Seleccione ese nuevo controlador de vista.
  3. Ir al esquema del documento.
  4. Verifique los contenidos del controlador.
  5. Si el nuevo controlador de vista no tiene un elemento de navegación, copie el elemento de navegación del anterior controlador de vista y péguelo en el nuevo controlador de vista.
  6. guardar y limpiar el proyecto.

También puede agregar varios botones usando rightBarButtonItems

-(void)viewDidLoad{

    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"button 1" style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD1:)];
    UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"button 2" style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD2:)];

    self.navigationItem.rightBarButtonItems = @[button1, button2];
}

@Artilheiro: si es un proyecto basado en la navegación, puede crear BaseViewController. Todas las demás vistas heredarán esta BaseView. En BaseView puede definir métodos genéricos para agregar el botón derecho o cambiar el texto del botón izquierdo.

ex:

  

@interface BaseController: UIViewController {

     

}   - (nulo) setBackButtonCaption: (NSString *) subtítulo;

     

(void) setRightButtonCaption: (NSString *) caption selectot: (SEL) selector;

     

@end   // En BaseView.M

     

(void) setBackButtonCaption: (NSString *) caption   {

UIBarButtonItem *backButton =[[UIBarButtonItem alloc] init];

backButton.title= caption;
self.navigationItem.backBarButtonItem = backButton;
[backButton release];
  

}   - (nulo) setRightButtonCaption: (NSString *) caption selectot: (SEL) selector   {

  UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] init];
rightButton.title = caption;

rightButton.target= self;

[rightButton setAction:selector];

self.navigationItem.rightBarButtonItem= rightButton;

[rightButton release];
  

}

Y ahora en cualquier vista personalizada, implemente esta vista base, llame a los métodos:

  

@interface LoginView: BaseController {

En algunos métodos, llame al método base como:

  

SEL sel = @selector (switchToForgotPIN);

     

[super setRightButtonCaption: @ " Olvidé mi PIN " selectot: sel];

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top