将一个UIButtons数组添加到navigationItem.rightBarButtonItem会导致NSInvalidArgumentException

Ala*_*lan 13 iphone xcode cocoa-touch

我试图在导航栏的右侧添加一个2个按钮的数组,但是当我运行代码时出现异常.

'NSInvalidArgumentException',原因:' - [UIButton isSystemItem]:发送到实例的无法识别的选择器

我的代码非常简单:

   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];
Run Code Online (Sandbox Code Playgroud)

我在iPhone 5.0模拟器上运行它.任何的想法??提前致谢.人

jrt*_*ton 29

你不能直接添加UIButtons.您需要首先将它们包装起来UIBarButtonItems- 没有编译器警告,因为您只传递一个数组.

使用创建条形按钮项目initWithCustomView:,将按钮作为自定义视图传递.或者,根据按钮中的内容,直接创建条形按钮项.


aop*_*fan 10

这里的技巧是使用UIBarButtonItem对象而不是UIButton对象.UIBarButtonItems可以从UIButtons创建,如下所示:

UIBarButtonItem *myItem = [[UIBarButtonItem alloc] initWithCustomView:uibuttonObject];
Run Code Online (Sandbox Code Playgroud)

但是,当UIBarButtonItems看起来很漂亮时,在导航栏中使用UIButton通常是一个坏主意.考虑访问UIBarButtonItem类参考.