我有2个VC,LoadViewController和HomeViewController。这是在我的LoadViewController中:

class LoadViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("init")
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
        self.present(nextViewController, animated: false)
    }
    deinit {
        print("deinit")
    }
}

我的HomeViewController中没有代码。我从未见过打印“deinit”,并且很好奇为什么控制器不会将其自身从内存中删除。我只想显示一个新的viewcontroller,并删除“旧” viewcontroller。

最佳答案

在视图控制器中调用present不会取消初始化当前视图控制器,因为当前视图控制器只是变成了“正在呈现”的视图控制器。要切换视图控制器,请在您的应用程序委托中添加以下内容:

func presentHome() {
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
    self.window?.rootViewController = nextViewController
    self.window?.makeKeyAndVisible()
}

func presentLoad() {
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "LoadViewController") as! LoadViewController
    self.window?.rootViewController = nextViewController
    self.window?.makeKeyAndVisible()
}

您可以在应用程序中的任何位置调用(UIApplication.shared.delegate as! AppDelegate).presentHome()来显示主视图控制器。

09-28 06:32