UIBarButtonItem target-action does not invoke
-
21-06-2021 - |
Domanda
- (void)viewDidLoad
{
[super viewDidLoad];
//Load the image
UIImage *buttonImage = [UIImage imageNamed:@"1.png"];
//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
//sets the frame of the button to the size of the image
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
//creates a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
customBarItem.target = self;
customBarItem.action = @selector(click:);
self.toolbarItems = [NSArray arrayWithObjects:customBarItem, nil];
}
- (void)click:(id)sender {
NSLog(@"action");
}
I think my console will print "action" when I push down the barItem. However "action" is not printed. Did I miss anything? Thanks for advance!
Soluzione
I believe the problem is that you are using a UIButton
for the [[UIBarButtonItem alloc] initWithCustomView
when you should simply pass a UIView
, the action is probably going to the UIButton
and not the UIBarButtonItem
.
Instead do this:
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:myImageView];
Altri suggerimenti
Try this
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Click ME!" style:UIBarButtonItemStyleBordered target:self action:@selector(click)];
.
.
.
-(void)click{
NSLog("hello");
}
I think you're trying to do something more like this:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button setFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];
[button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow