通过编程返回button转到上一个视图

我有一个UIBarButtonItem,并希望以编程方式设置前一个控制器的行动(在我的情况下,我以前的视图是一个UITableViewController)。

下面是我目前使用的代码来创build栏button项目,尽pipebutton还没有转到上一个视图。

UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:nil action:nil]; UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Website"]; item.leftBarButtonItem = leftButton; item.hidesBackButton = YES; [myBar pushNavigationItem:item animated:NO]; 

在你的控制器中添加以下代码,在- (void)viewDidLoad函数中:

调用[self addBackButtonWithTitle:@"back"]; 如果你想自定义带标题的后退button。

[self addBackButtonWithImageName:@"back_button_image_name"]; 如果你想要图像自定义后退button。

 /** * @brief set lef bar button with custom title */ - (void)addBackButtonWithTitle:(NSString *)title { UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed:)]; self.navigationItem.leftBarButtonItem = backButton; } /** * @brief set left bar button with custom image (or custom view) */ - (void)addBackButtonWithImageName:(NSString *)imageName { // init your custom button, or your custom view UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; backButton.frame = CGRectMake(0, 0, 40, 22); // custom frame [backButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal]; [backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; // set left barButtonItem with custom view self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton]; } - (void)backButtonPressed:(id)sender { [self.navigationController popViewControllerAnimated:YES]; } 

你可以写在你的viewDidLoad方法:

 UIBarButtonItem *btn=[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(btnClick)]; self.navigationItem.leftBarButtonItem=btn; 

然后使用这个:

 // call of method -(void)btnClick { [self.navigationController popViewControllerAnimated:YES]; } 

[self dismissViewControllerAnimated:YES completion:nil];