通过编程使返回按钮返回上一个视图

10

我有一个UIBarButtonItem,想要以编程方式设置跳转到前一个视图控制器的操作(在我的情况下,我的前一个视图是UITableViewController)。

以下是我目前使用的代码来创建这个导航栏按钮,但该按钮尚未跳转到上一个视图。

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];

你的代码中哪里显示了选择器? - El Tomato
UINavigationBar *myBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 64)]; [self.view addSubview:myBar];UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:nil action:nil]; [leftButton addTarget:self action:@selector(method) - Colton Anglin
3个回答

16

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

如果您想要自定义带标题的返回按钮,请调用 [self addBackButtonWithTitle:@"back"];

或者,如果您想要使用图像自定义返回按钮,请调用 [self addBackButtonWithImageName:@"back_button_image_name"];

/**
 *  @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];
}

11
你可以在你的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];
}

3

[self dismissViewControllerAnimated:YES completion:nil];

意思是:关闭当前视图控制器并返回到上一个控制器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接