[英]Swift UICollectionView updating cell label on click not updating live
我一直試圖弄清楚如何實時更新一個uicollectionview。
我嘗試使用reloadData,reloadItems和reloadSections來使用許多不同的方法來完成這項工作。 而不是使用DispatchQueue.main.async。
我無法弄清楚如何讓用戶選擇其中一個單元格,以便在用戶面前更新該單元格的內容。 特別是根據單元格上的點擊使標簽文本變為粗體而不是粗體。
這是我在swift中設置的標簽:
let nameLabel: UILabel = {
let label = UILabel()
label.text = ""
return label
}()
這是collectionview的didselectitem
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! FilterCollectionViewCell
let selected = ViewController.brands[indexPath.item]
if FilterLauncher.selectedOptions.contains(selected){
let loc = FilterLauncher.selectedOptions.firstIndex(of: selected)
FilterLauncher.selectedOptions.remove(at: loc!)
cell.nameLabel.font = UIFont.boldSystemFont(ofSize: 2.0)
DispatchQueue.main.async {
collectionView.reloadItems(at: [indexPath])
}
}
else{
FilterLauncher.selectedOptions.append(selected)
cell.nameLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
DispatchQueue.main.async{
self.collectionView.reloadItems(at: [indexPath])}
}
}
它最終會將所選單元格的文本更改為粗體,但它會延遲執行。 當我試圖選擇第一個粗體時,我需要嘗試選擇另一個單元格。 當我第一次選擇單元格時,它會閃爍我想要的更改,但隨后又返回。
我認為你不需要在選擇后調用collectionView.reloadItems(at: [indexPath])
。 直接訪問單元格的標簽應該進行更改而無需重新加載單元格。
我的猜測是你在cellForItemAt
有一些出列代碼, cellForItemAt
字體設置為正常,所以當你點擊一個單元格時,它的標簽會被設置為粗體,但是當你重新加載它時會立即恢復正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.