后退按钮以编程方式转到上一个视图

时间:2014-02-19 01:58:33

标签: ios objective-c button

我有一个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];

3 个答案:

答案 0 :(得分:14)

在控制器的- (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];
}

答案 1 :(得分:10)

您可以在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];
}

答案 2 :(得分:3)

[self dismissViewControllerAnimated:YES completion:nil];

相关问题