UIBarButtonItem - 如何弹出“完成”按钮?

时间:2012-03-01 06:43:16

标签: ios uibarbuttonitem navigationcontroller

我有一个带有“完成”按钮的导航控制器。当用户完成表单后,按“完成”,我希望该视图从堆栈中弹出并返回主菜单。

这是我到目前为止的代码:

UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
                                                                  style:UIBarButtonItemStylePlain 
                                                                 target:self 
                                                                 action:[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES]];          
self.navigationItem.rightBarButtonItem = anotherButton;

请帮忙!谢谢

3 个答案:

答案 0 :(得分:3)

你怎么试试这个:

UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
                                                               style:UIBarButtonItemStylePlain 
                                                                 target:self 
                                                                 action:@selector(onClickOfDone);          
self.navigationItem.rightBarButtonItem = anotherButton;

现在在名为 onClickOfDone

的方法中编写popViewController逻辑
- (void)onClickOfDone {
[self.navigationController popViewControllerAnimated:YES];
}

如果你的弹出只有一个级别,那么上面的代码会有所帮助。如果要指定要将其弹出的控制器,则可以使用

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES]

编辑:

您也可以使用SystemItem进行完成:

UIBarButtonItem *aDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                                             target:self action:@selector(onClickOfDone)];
self.navigationItem.rightBarButtonItem = aDoneButton;
[aDoneButton release];

答案 1 :(得分:1)

1)定义与self对应的类的新方法。例如,

- (void)closeView
{
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
}

2)创建按钮时设置适当的选择器:

UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
                                                              style:UIBarButtonItemStylePlain 
                                                             target:self 
                                                             action:@selector(closeView)];          
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release]; // and don't forget to clear memory

答案 2 :(得分:0)

您的代码是正确的只需创建一个函数并在该函数内部编写弹出代码,然后使用@selector执行该函数。