如何模拟返回未显示的ViewController

时间:2019-02-07 11:29:18

标签: ios uiviewcontroller

我有一个带登录屏幕的iOS应用程序。用户登录后,我使用presentViewController转到应用程序的主屏幕。如果用户从主屏幕注销,则我dismiss当前(主)视图控制器返回登录屏幕。效果很好,并且将标准动画用于“模态呈现”。

现在,我要对此进行修改,以便如果用户已经登录,则跳过登录屏幕。因此,在我的应用程序委托中,我执行以下操作(伪代码)

if (user logged in)
   presentViewController(mainVC)
else
   presentViewController(loginVC)

问题:如果用户已经登录并且我直接显示了主视图控制器,那么我将无法再“关闭”它以返回登录视图控制器(因为从未显示过)。然后如何“模拟”返回登录VC?

在Android中,可以通过手动手动构建活动的“后退堆栈”(https://developer.android.com/training/implementing-navigation/temporal)来实现类似的目的。 iOS中有与此等效的东西吗?

2 个答案:

答案 0 :(得分:0)

您必须检查应用程序启动。用户是否登录。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


if isUserLoggedIn {
        //Set Main ViewController
        self.window?.showAuthenticationVC

    } else {
        //Optional.. But you can set here Logic VC
        self.window?.showMainController()
    }
    return true
}

isUserLoggedIn标志,用于管理已登录或未登录的用户。您可以将该值存储在UserDefaults中。

为已登录和已注销用户管理rootViewController。

extension UIWindow {



 func showAuthenticationVC() {

        self.makeKeyAndVisible()
        let authenticationVC : LoginController = LoginController()
        let navigationController = UINavigationController(rootViewController: authenticationVC)
        self.rootViewController = navigationController

    }

    func showMainController() {
        self.makeKeyAndVisible()
        let authenticationVC : MainController = MainController()
        let navigationController = UINavigationController(rootViewController: authenticationVC)
        self.rootViewController = navigationController
    }

}

并且在登录操作时。使用AppDelegate showMainController()设置window。与使用AppDelegate的showAuthenticationVC()属性注销window时的调用相同。

希望对您有帮助!

答案 1 :(得分:0)

我已经多次遇到这种类型的问题。我的处理方式是在应用程序的开头使用虚拟VC,并将其命名为StartupVC。在StartupVC中,我添加了逻辑以检查用户是否已登录。如果用户已登录,我会将其发送到主屏幕。如果没有,我会显示登录屏幕。

现在,当用户注销时,我将视图控制器弹出到StartupVC。在启动VC中,我将登录检查登录名设置为import React, { Component } from 'react'; import MyComponent from './MyComponent/index'; import WithFetch from './../../../../services/withFetching'; class TableSources extends Component { componentWillMount() { const params = {} WithFetch('my URL')(MyComponent).get(params) } render() { return (...) } } export default TableSources; 方法,因此,一旦再次显示StartupVC,就会将用户带到登录屏幕。

要使过渡平滑,您可以在注销后导航回登录时关闭动画。