如何删除以前的 ViewController

2024-05-23

我是一名学生,对编程还很陌生。我正在尝试在业余时间学习 Objective-C/Swift。我使用 spriteKit 和 swift 制作了一个游戏,有多个菜单/场景。

我正在尝试从一个视图控制器转换到另一个视图控制器。为此,我使用了以下代码:

@IBAction func PlayButtonPressed(sender: AnyObject) {
    let playStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc : UIViewController = playStoryboard.instantiateViewControllerWithIdentifier("playGame") as UIViewController
    self.presentViewController(vc, animated: true, completion: nil)
}

这适用于过渡到新的 VC 场景,但是,我相信以前的 VC 仍在堆栈中并占用内存,从而减慢了我的程序速度。

我读过一些其他帖子,您可以使用导航控制器来删除 VC。但是,我没有导航控制器;仅查看控制器。我看过一些关于removeFromParentViewController() and view.removeFromSuperview(),但我真的不知道如何实现它。除此之外,我没有找到我正在寻找的答案。

所以我要问的问题是如何从堆栈中删除以前的 VC?任何帮助将不胜感激! (希望能快速提供帮助,但 Objective-C 也会有帮助)提前谢谢您!

备注供参考:我相信在 Objective-C 中我的代码会是这样的:

-(IBAction) PlayButtonPressed: (id) sender {
    UIStoryboard *playStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [playStoryboard instantiateViewControllerWithIdentifier:@"playGame"];
    [self presentViewController:vc animated:YES completion:nil];
}

正如我可以假设的那样,屏幕上呈现的视图控制器是从主故事板自动实例化的,或者是通过设置应用程序的window.rootViewController财产。

无论哪种情况,您都可以设置rootViewController再次成为你的vc。要更改应用程序的 rootViewController,您需要替换以下代码行:

self.presentViewController(vc, animated: true, completion: nil)

...使用以下选项之一。

没有过渡动画的“导航”:

Objective-C

UIWindow *window = (UIWindow *)[[UIApplication sharedApplication].windows firstObject];
window.rootViewController = vc;

Swift

let window = UIApplication.sharedApplication().windows[0] as UIWindow;
window.rootViewController = vc;

带过渡动画的“导航”:

Objective-C

UIWindow *window = (UIWindow *)[[UIApplication sharedApplication].windows firstObject];
[UIView transitionFromView:window.rootViewController.view
                    toView:vc.view
                  duration:0.65f
                   options:UIViewAnimationOptionTransitionCrossDissolve // transition animation
                completion:^(BOOL finished){
                    window.rootViewController = vc;
                }];

Swift

let window = UIApplication.sharedApplication().windows[0] as UIWindow;
UIView.transitionFromView(
    window.rootViewController.view,
    toView: vc.view,
    duration: 0.65,
    options: .TransitionCrossDissolve,
    completion: {
        finished in window.rootViewController = vc
    })

Remarks:一旦 rootViewController 值发生更改,您的原始视图控制器引用计数应该变为 0,因此它将从内存中删除!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何删除以前的 ViewController 的相关文章

随机推荐