自定义按钮出错

时间:2013-07-31 22:12:50

标签: ios uibutton

我有一个错误:

2013-08-01 01:09:18.433 VstupHelper[28332:11303] -[VHMasterViewController popViewController:]: unrecognized selector sent to instance 0x7566410
2013-08-01 01:09:18.434 VstupHelper[28332:11303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[VHMasterViewController popViewController:]:

这是我的代码:

UIButton *bt=[UIButton buttonWithType:UIButtonTypeCustom];
    [bt setFrame:CGRectMake(0, 0, 50, 30)];
    [bt setImage:[UIImage imageNamed:@"menu.png"] forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(popViewController:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithCustomView:bt];
    self.navigationItem.leftBarButtonItem=leftButton;

    self.navigationItem.leftBarButtonItem.target = self.revealViewController;
    self.navigationItem.leftBarButtonItem.action = @selector(revealToggle:);

我不擅长英语,所以如果我很难理解,我会道歉。

1 个答案:

答案 0 :(得分:2)

你有几个问题:

1)当你应该在你的popViewController:上调用它时,你正在调用UIViewController我认为属于UINavigationController的子类。

2)popViewController:取一个bool值来判断是否为该转换设置动画。通过该操作,默认情况下会传递给发件人。

3)然后,您为该按钮重新分配目标和操作(但在使用UIBarButtonItem初始值设定项创建initWithCustomView:时,不会调用这些内容:See docs)。


如何解决这个问题:

1)调用为按钮处理程序创建的方法:

UIButton *bt=[UIButton buttonWithType:UIButtonTypeCustom];
[bt setFrame:CGRectMake(0, 0, 50, 30)];
[bt setImage:[UIImage imageNamed:@"menu.png"] forState:UIControlStateNormal];
[bt addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithCustomView:bt];
self.navigationItem.leftBarButtonItem=leftButton;

2)在该方法中,弹出视图控制器,或执行您想要执行的任何操作:

- (void)buttonTouched:(id)sender 
{
    [self.navigationController popViewController:YES]; 
    //Or what you assigned to the button action:
    [self.revealViewController revealToggle:(not sure what you're supposed to have here)];
}