Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an array of UIButtons to navigationItem.rightBarButtonItem results in NSInvalidArgumentException

I am trying to add an array of 2 buttons to the right of a navigation bar, but I get a exception when I run the code.

'NSInvalidArgumentException', reason: '-[UIButton isSystemItem]: unrecognized selector sent to instance

My code is pretty simple really:

   UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,45)];
   label.backgroundColor=[UIColor clearColor];
   label.text = @"Test 2 Buttons";

   UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
   button1.frame = CGRectMake(00.0f, 0.0f, 32.0f, 32.0f);

   UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
   button2.frame = CGRectMake(00.0f, 0.0f, 32.0f, 32.0f);

   NSArray *rightBarButtons = [[NSArray alloc] initWithObjects:button2, button1, nil];


   UINavigationItem* navItem = self.navigationItem;
   navItem.titleView = label;
   navItem.rightBarButtonItems = rightBarButtons;
   [rightBarButtons release];
   [label release];

I am running it on the iPhone 5.0 simulator. Any idea?? Thanks in advance. Al

like image 258
Alan Avatar asked Nov 26 '11 16:11

Alan


1 Answers

You can't directly add UIButtons. You need to wrap them as UIBarButtonItems first - there is no compiler warning since you are only passing an array.

Create the bar button items using initWithCustomView:, passing in your button as the custom view. Or, depending on what is in your buttons, create bar button items directly.

like image 83
jrturton Avatar answered Sep 18 '22 15:09

jrturton