TabBar / CollectionView崩溃

时间:2019-03-21 17:49:42

标签: ios swift

所以我有一个mainController,它继承自UITabBarController。在内部,我像这样设置视图控制器:

func setupControllers() {
    let chatController = UINavigationController(rootViewController: ChatController())

    let homeController = UINavigationController(rootViewController: HomeController())



    viewControllers = [chatController, homeController]
}

在“ homeController”视图控制器内部,我添加了一个collectionView子视图,该视图在viewDidLoad函数中设置。

HomeController类:UIViewController {

let userCollectionView = UserCollectionView()

override func viewDidLoad() {
    super.viewDidLoad()

    setupSubviews()
}

private func setupSubviews() {

    view.addSubview(userCollectionView)
    userCollectionView.protocolDelegate = self
    userCollectionView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor, padding: .zero, size: .init(width: view.frame.width, height: 108))
}
}

在UserCollectionView内部,在viewDidLoad内部,我有一些firebase观察器,这些查询通过'insertItems / reloadItems'方法查询并提取数据以存储在collectionView中。

当我加载应用程序时,它崩溃了。而且我将其归结为userCollectionView说“部分无效的项目”等,因为我一次加载一个collectionView单元,而不是通过self.reloadData()重新加载完整的collectionView。

当我将viewControllers的加载顺序更改为[homeController,chatController]时,它可以正常工作,因为这是第一个加载的viewController。但是,当我将其切换到[chatController,homeController]时,它崩溃了。

我已经在viewWillAppear中尝试过setupSubviews,但是该应用仍然崩溃。

即使删除了colletionView的设置,也只有实例:

let userCollectionView = UserCollectionView()

崩溃。

崩溃错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0.  The number of items contained in an existing section after the update (1) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

我知道与里面的collectionView'insertItems / reloadItems'函数有关,好像我删除了它们一样,没问题。我不明白为什么会崩溃,因为homeController仍在与所有方法/ firebase观察程序一起加载,以在其中流行userCollectionView。这只是应用启动时显示的初始viewController。

我将如何解决此问题?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

在viewDidAppear方法内添加了观察者函数。

这样,当按下homeController选项卡时,将调用观察者并更新collectionView。

我很好奇为什么它仍然会崩溃,因为有数据要插入到collectionView中。为了有效,正在更新其子视图的viewController是否必须可见?

相关问题