gpt4 book ai didi

Swift View 似乎延迟加载到窗口层次结构中

转载 作者:行者123 更新时间:2023-11-30 11:01:24 25 4
gpt4 key购买 nike

发生了一件非常奇怪的事情,似乎我的初始 View Controller 已加载,执行其逻辑,并且除了实际 View 本身之外的所有内容都没有添加到层次结构中,直到其他一切发生为止。

    protocol OnboardDisplayLogic: class
{
func handleUserConfirmation(viewModel: OnboardModels.CheckForUser.ViewModel)
}

class OnboardViewController: UIViewController, OnboardDisplayLogic {

var interactor: OnboardInteractor?
var router: (NSObjectProtocol & OnboardRoutingLogic & OnboardDataPassing)?

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}

//MARK: Setup

private func setup() {
let viewController = self
let interactor = OnboardInteractor()
let presenter = OnboardPresenter()
let router = OnboardRouter()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
presenter.viewController = viewController
router.viewController = viewController
router.dataStore = interactor
}

private func setupView() {
view.backgroundColor = UIColor.brown
}

//MARK: Routing

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let scene = segue.identifier {
let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
if let router = router, router.responds(to: selector) {
router.perform(selector, with: segue)
}
}
}

//MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()

setupView()
interactor?.checkForUser()
}

func handleUserConfirmation(viewModel: OnboardModels.CheckForUser.ViewModel) {
if let username = viewModel.username {
print("Logged in user: \(username)")
router?.routeToUserFeed(segue: nil)
} else {
print("No user logged in")
router?.routeToLoginRegister(segue: nil)
}
}

我认为它延迟的原因是,虽然我已将 View 背景颜色设置为棕色,但在 print("user notlogin") 代码中使用断点,我将其打印到控制台,因为交互器确定没有用户登录,但 View 保持白色。直到我跨过去并完成所有代码的运行后,屏幕才会变成棕色。

因此我收到错误

Warning: Attempt to present ... whose view is not in the window hierarchy!

因为某些东西阻止 View 添加到最后。

最佳答案

实际 View 在进入 View Controller 生命周期之前不会加载。如果您需要在将 View 添加到 super View 的层次结构之前将其加载到设置中,只需使用 View 的 getter (let _ = viewController.view)。

UIViewController也有loadView()方法,查看:Apple documentation .

我们在使用 Clean Swift 时也遇到过此类问题。正确的工作方式是从 Storyboard实例化并仅使用正常的 segues/生命周期,就像 MVC 对 Apple 示例所做的那样。

您应该从 Storyboard实例化 let viewControllerToPush = Storyboard?.instantiate... 并使用该 View Controller ,而不是执行 let viewControllerToPush = MyVCSublass(...) .

关于Swift View 似乎延迟加载到窗口层次结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53321182/

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