gpt4 book ai didi

ios - 在 swift 中以编程方式创建 navigationController 时,ViewController 出现多次

转载 作者:行者123 更新时间:2023-11-28 16:10:14 25 4
gpt4 key购买 nike

我一直在以编程方式完全从头开始创建我的应用程序,没有使用 Storyboard

我的应用程序与 Firebase 集成,并使用 Facebook 登录。

我的设置相当简单:

  1. Launch the app -> takes you to the first VC called WelcomeViewController.
  2. There is a check that happens in the viewDidLoad method to see if a user is already signed in and exists. If there is, it sends you straight to the second VC called FilmsViewController
  3. The FilmsViewController is a collectionViewController that displays films. The user can press a film, and it takes them to more information about that film.

(作为引用,我已经在我的应用程序中登录了 Facebook)

我有一个当前问题,当上面的第 2 步发生时,它会转换到 FilmsViewController,但它会转换 2 或 3 次。所以你看到新的 VC 出现了 2 或 3 次,然后内容加载了。如果您按下导航栏中的 Back 按钮,它会带您返回到它加载的 2 或 3 个 viewController,然后再返回到 WelcomeViewController

我的观点如下。

AppDelegate.swift 中:

var window: UIWindow?
var navController: UINavigationController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

navController = UINavigationController()
let firstViewController: WelcomeViewController = WelcomeViewController()
self.navController!.pushViewController(firstViewController, animated: true)

window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = navController
window?.makeKeyAndVisible()

return true

}

viewDidLoadWelcomeViewController 中:

FIRAuth.auth()?.addStateDidChangeListener { auth, user in

if let user = user {

// User is signed in.
// Direct the user to the home screen

let toFilmListVC = FilmsViewController(collectionViewLayout: UICollectionViewFlowLayout())
self.navigationController?.pushViewController(toFilmListVC, animated: true)

} else { ...
}
}

我找了很多解决方案 - 但一无所获。我只找到一篇关于这个问题的帖子,有人说解决方案是更改该 Controller 的类名,我已经这样做了,但没有任何改变。

谁能帮我解决这个问题?谢谢。

最佳答案

addStateDidChangeListener 可能被调用了多次。

你应该修改它来检查一个 FilmsViewController 是否已经被推送,以防止推送另一个:

FIRAuth.auth()?.addStateDidChangeListener { auth, user in

if let user = user {

// User is signed in.
// Direct the user to the home screen

// Only push one FilmsViewController onto the navigation stack!
var shouldPush = true
if let navigationController = self.navigationController {
for viewController in navigationController.viewControllers {
if viewController is FilmsViewController {
shouldPush = false
}
}
}

if shouldPush {
let toFilmListVC = FilmsViewController(collectionViewLayout: UICollectionViewFlowLayout())
self.navigationController?.pushViewController(toFilmListVC, animated: true)
}
} else { ...
}
}

关于ios - 在 swift 中以编程方式创建 navigationController 时,ViewController 出现多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39669682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com