collectionView 不会在 viewDidLoad 中重新加载数据,但它在 viewWillAppear 中有效

collectionView doesn't reloadData in viewDidLoad but it works in viewWillAppear

我使用以下代码从标签栏显示了一个名为 NewOrderVC 的 viewController:

if let selectedAnn = mapView.selectedAnnotations[0] as? StoreAnnotation {
                let id = selectedAnn.storeModel!.id
                let vc = NewOrderVC(storeID: id)          
                vc.modalPresentationStyle = .fullScreen
                self.show(vc, sender: nil)
            }

使用 getStore 函数,我从 firebase 下载了一些代码。 新订单VC:

override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.main.async {
            self.getStore(id: self.id)
        }

        initializeHideKeyboard()
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        layout.itemSize = CGSize(width: view.width / 2 - 15,
                                 height: view.width - 30)
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)      
        guard let collectionView = collectionView else {
            return
        }
        collectionView.register(ProductCollectionViewCell.self, forCellWithReuseIdentifier: ProductCollectionViewCell.identifier)
        collectionView.register(HeaderCollectionReusableView.self,
                                 forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                                 withReuseIdentifier: HeaderCollectionReusableView.identifier) 
        collectionView.delegate = self
        collectionView.dataSource = self
        view.addSubview(collectionView)
        view.addSubview(finishButton)
        collectionView.backgroundColor = .systemBackground

在 viewDidLoad 中,collectionView.reloadData 不起作用。当视图控制器出现时,我看不到 collectionView。

        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }      
    } 

如果我使用选项卡栏图标更改 viewController,则会出现 collectionView 并在其中加载对象。

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        collectionView.delegate = self
        collectionView.dataSource = self

        DispatchQueue.main.async {         
            self.collectionView.reloadData()
        }
    }

这是 getStore 函数。它是这样工作的。

private func getStore(id: String)  {
        DatabaseManager.shared.showProducts(id: id) { downloaded in
            switch downloaded {
            case .failure(_):
                self.makeAlert(title: "Error", message: "Products could not download!")
                break
            case.success(let products):
                self.store = products
            }
        }
        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
        
}

感谢您的帮助。

如果您在 collectionView 中显示的数据来自 getStore 函数,那么您需要在数据到达后重新加载 CollectionView,而不是在 viewDidLoad 和 ViewWillAppear 中