以编程方式使后退按钮转到上一个视图
Posted
技术标签:
【中文标题】以编程方式使后退按钮转到上一个视图【英文标题】:Make back button go to the previous view programmatically 【发布时间】:2014-02-19 01:58:33 【问题描述】:我有一个 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];
【问题讨论】:
你的行在哪里显示选择器? UINavigationBar *myBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 64)]; [self.view addSubview:myBar]; UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:nil action:nil]; [leftButton addTarget:self action:@selector(method) 【参考方案1】:在您的控制器中,- (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];
【讨论】:
【参考方案2】:你可以在你的 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】:[selfdismissViewControllerAnimated:YES 完成:nil];
【讨论】:
以上是关于以编程方式使后退按钮转到上一个视图的主要内容,如果未能解决你的问题,请参考以下文章
后退按钮关闭应用程序而不是转到上一个片段 android 导航组件