繁体   English   中英

如何在视图控制器中创建后退按钮以转到父视图控制器

[英]How to create a back button in a view controller to go to parent view controller

嗨,我有一个带有容器的视图控制器,当用户点击集合视图单元格时,在容器中有一个带有集合视图的子视图,它将我发送到详细视图控制器,但是现在我要做的是在我的容器中添加一个后退按钮。详细信息视图控制器,将我发送到parentViewController

在此处输入图片说明

案例1 :放松Segue

这将根据您的情况完美运行:

iOS Unwind Segue

展开Segues提供了一种“展开”导航堆栈并指定要返回的目的地的方法。

情况2 :PopToRootViewController

如果父视图也是根视图控制器,则可以使用popToRootViewControllerAnimated:YES轻松返回。

创建自己的后退按钮,使用backButtonTouch方法将其添加到导航栏。

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Back", nil) style:UIBarButtonItemStyleDone target:self action:@selector(backButtonTouch:)]; 

将以上代码添加到viewDidLoad

-(void)backButtonTouch:(id)sender{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
  1. 如果要自定义返回按钮,请先隐藏导航栏

    [self.navigationController setNavigationBarHidden:YES];

  2. 现在添加一个按钮,并创建其touchUpInside事件,在该事件中弹出控制器

    [self.navigationController popViewControllerAnimated:YES];

在“后退”按钮操作上,添加以下行:

[self.navigationController popToRootViewControllerAnimated:YES];

这会将您移至rootViewController

这是我的代码,返回到父视图控制器

 - (IBAction)ActionbtnBack:(id)sender {
        int flag = 0;
        for (UIViewController *controller in [[self.navigationController.viewControllers reverseObjectEnumerator] allObjects]) {
            NSLog(@"> %@",[controller class]);
            if ([controller isKindOfClass:[YourParentviewcontroller class]]) {
                flag=1;
                [self.navigationController popToViewController:controller
                                                      animated:YES];
                break;
            }
            else if ([controller isKindOfClass:[YourParentviewcontroller class]]) {
                flag=1;
                [self.navigationController popToViewController:controller
                                                      animated:YES];
                break;
            }
        }
        if (flag == 0) {
            YourParentviewcontroller *MoreVc = [[YourParentviewcontroller alloc] initWithNibName:@"parentViewcontrollerIdentifier" bundle:nil];
            [self.navigationController pushViewController:MoreVc animated:YES];
        }
    }

在此处输入图片说明

暂无
暂无

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

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