繁体   English   中英

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

[英]Make back button go to the previous view programmatically

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

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

call [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];
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM