![](/img/trans.png)
[英]Changing NSLayoutContraint constant in viewDidLoad or viewWillAppear don't works
[英]collectionView doesn't reloadData in viewDidLoad but it works in viewWillAppear
我使用以下代碼從標簽欄中顯示了一個名為 NewOrderVC 的視圖控制器:
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 中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.