Cómo establecer el objetivo y la acción para UIBarButtonItem en tiempo de ejecución


Intentó esto pero solo funciona para UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
Author: Haroldo Gondim, 2010-02-25

9 answers

Simplemente establezca las propiedades target y action de UIBarButtonItem directamente.

 91
Author: Ole Begemann,
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
2010-02-25 11:41:20

UIBarButtonItem no tiene el mismo método addTarget, por lo que debe configurarlos directamente de la siguiente manera

btn.target = self;
btn.action = @selector(barButtonCustomPressed:);

...

// can specify UIBarButtonItem instead of id for this case
-(IBAction)barButtonCustomPressed:(UIBarButtonItem*)btn 
{
    NSLog(@"button tapped %@", btn.title);
}
 18
Author: mihai,
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-09-11 20:36:59

Me encontré con un problema similar... Supongo que quiere decir que si su UIButton no es parte de su UITabBar para llamar a btnClicked, entonces funciona apropiadamente. Si este es el problema que está proponiendo, compruebe su método btnClicked y cámbielo de:

-btnClicked:(id)sender

A

-(void) btnClicked:(id)sender

Que, y declarar btnClicked en el archivo de cabecera...

Por si sirve de algo, así es como configuro un botón en tabbarbuttonitem:

UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button.png"] style:UIBarButtonItemStylePlain target:self action:@selector(btnClicked:)];
 14
Author: J. Dave,
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
2010-02-28 04:56:49
  UIBarButtonItem *barListBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(getTruckStopListAction)];   
    self.navigationItem.rightBarButtonItem = barListBtn;
    [barListBtn release];
 7
Author: sinh99,
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
2012-03-14 07:01:57

Si necesita esto suficientes veces en su código, es bueno continuar y extender UIBarButtonItem lo que he hecho a continuación en Swift. :)

import UIKit

extension UIBarButtonItem {
    func addTargetForAction(target: AnyObject, action: Selector) {
        self.target = target
        self.action = action
    }
}

Como ejemplo, con self como UIViewController, simplemente llamarías:

self.myBarButtonItem.addTargetForAction(self, action: #selector(buttonPressed(_:))
 6
Author: serenn,
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-09-09 18:02:34

Conjunto target y action de su UIBarButtonItem

Swift 4

button.target = self
button.action = #selector(action)

@objc func action (sender:UIButton) {
    print("action")
}
 6
Author: Haroldo Gondim,
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-10-10 12:40:25

@wp42 Funciona hoy.

Una forma ingeniosa de hacer esto en objective-C es agregar una categoría a la clase UIBarButtonItem:

.h file

#import <UIKit/UIKit.h>

@interface UIBarButtonItem (addons)

-(void)addTarget:(id)target andAction:(SEL)action;

@end

.m file

#import "UIBarButtonItem+addons.h"

@implementation UIBarButtonItem (addons)

-(void)addTarget:(id)target andAction:(SEL)action{
   [self setTarget:target];
   [self setAction:action];
}

@end

En la práctica:

[myBtn addTarget:self andAction:@selector(myFunction:)];
 1
Author: Itai Spector,
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-09-08 19:58:08

Si está agregando programáticamente el UIBarButtonItem, la mejor manera de establecer el objetivo y la acción es inicializar el botón con uno de los siguientes métodos:

UIBarButtonItem *customButton = [[UIBarButtonItem alloc] initWithImage:<#(UIImage)#> style:<#(UIBarButtonItemStyle)#> target:<#(id)#> action:<#(SEL)#>

UIBarButtonItem *customButton = [UIBarButtonItem alloc] initWithTitle:<#(NSString *)#> style:<#(UIBarButtonItemStyle)#> target:<#(id)#> action:<#(SEL)#>

UIBarButtonItem *customButton = [UIBarButtonItem alloc] initWithImage:<#(UIImage *)#> landscapeImagePhone:<#(UIImage *)#> style:<#(UIBarButtonItemStyle)#> target:<#(id)#> action:<#(SEL)#>
 0
Author: Adam Cooper,
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-01-06 20:47:31

Es posible que desee probar el método addTarget.

 -4
Author: David Carvalho,
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
2010-11-09 10:21:16