0
- (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!

Hamed Rajabi Varamini
  • 3,439
  • 3
  • 24
  • 38
coolhongly
  • 53
  • 3
  • 10

3 Answers3

2

Try this

UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Click ME!" style:UIBarButtonItemStyleBordered target:self action:@selector(click)];

.
.
.

-(void)click{
    NSLog("hello");
}
Hamed Rajabi Varamini
  • 3,439
  • 3
  • 24
  • 38
superGokuN
  • 1,399
  • 13
  • 28
1

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];
Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
1

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];
DJPlayer
  • 3,244
  • 2
  • 33
  • 40