后退按钮以编程方式转到上一个视图 [英] Make back button go to the previous view programmatically
问题描述
我有一个UIBarButtonItem,并希望以编程方式设置前一个控制器的动作(在我的例子中,我以前的视图是一个UITableViewController)。
I have a UIBarButtonItem and would like to programmatically set the action that goes to the previous controller (in my case, my previous view is a UITableViewController).
下面是我目前用来制作条形按钮项目的代码,虽然该按钮尚未转到上一个视图。
Below is my code that I am currently using to make the bar button item although the button doesn't go to the previous view yet.
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
function:
Add following code in your controller, in - (void)viewDidLoad
function:
call [self addBackButtonWithTitle:@back];
如果你想自定义带标题的后退按钮。
call [self addBackButtonWithTitle:@"back"];
if You want to custom backbutton with title.
或 [self addBackButtonWithImageName:@back_button_image_name];
如果您想要带有图像的自定义后退按钮。
or [self addBackButtonWithImageName:@"back_button_image_name"];
if You want custom backbutton with image.
/**
* @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];
}
这篇关于后退按钮以编程方式转到上一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!