I showed a viewController named NewOrderVC from a tab bar with this code:
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)
}
With getStore function, I download some codes from firebase. NewOrderVC:
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
In viewDidLoad, collectionView.reloadData does not work. I can't see collectionView when view controller appeared.
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
If I change the viewController with using tab bar icons, collectionView appear and objects loaded in it.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.delegate = self
collectionView.dataSource = self
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
This is getStore function. It works like this.
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()
}
}
Thank you for any help.
CodePudding user response:
If the data you are displaying in collectionView is coming from getStore function, then you need to reload CollectionView after the data comes rather then in viewDidLoad and ViewWillAppear