【发布时间】:2021-06-17 02:09:57
【问题描述】:
我正在通过在集合视图中点击按钮来更新类别图像。我有一个collectionView,当点击按钮并且图像发生变化时,它具有淡入动画。我也尝试使用reloadItem,但它仍然闪烁。
我发现问题是因为我在单元格更新中调用reloadData引起的,但是当按下按钮时我找不到正确的方法。
视图控制器
import UIKit
import CoreData
class WordsVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var wordsCategoryCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
wordsCategoryCollection.delegate = self
wordsCategoryCollection.dataSource = self
wordsCategoryCollection.isScrollEnabled = false
wordsCategoryCollection.backgroundColor = nil
roundCounter = 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return words.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WordsCategoryCell", for: indexPath) as? WordsCategoryCell {
cell.backgroundColor = UIColor.clear
cell.wordsBtn.tag = indexPath.row
cell.wordsBtn.addTarget(self, action: #selector(changeCategoryStatus), for: .touchUpInside)
cell.updateCell(word: words[indexPath.row])
return cell
}
return UICollectionViewCell()
}
@objc func changeCategoryStatus(_ sender: UIButton!) {
debugPrint(sender.tag)
if words[sender.tag].categoryIsEnable == true {
words[sender.tag].categoryIsEnable = false
words[sender.tag].categoryImageName.removeLast()
words[sender.tag].categoryImageName.append("F")
} else {
words[sender.tag].categoryIsEnable = true
words[sender.tag].categoryImageName.removeLast()
words[sender.tag].categoryImageName.append("T")
}
debugPrint("\(words[0].categoryImageName) - \(words[0].categoryIsEnable)")
debugPrint("\(words[1].categoryImageName) - \(words[1].categoryIsEnable)")
debugPrint("\(words[2].categoryImageName) - \(words[2].categoryIsEnable)")
wordsCategoryCollection.reloadData()
//wordsCategoryCollection.reloadItems(at: [IndexPath(row: sender.tag, section: 0)])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
getWordsForTheGame()
}
@IBAction func playBtn(_ sender: Any) {
performSegue(withIdentifier: "MainVC", sender: nil)
}
}
单元格
class WordsCategoryCell: UICollectionViewCell {
@IBOutlet weak var wordsBtn: UIButton!
func updateCell(word: word) {
let image = UIImage(named: word.categoryImageName)
wordsBtn.setTitle(nil, for: .normal)
wordsBtn.setImage(image, for: .normal)
}
}
GIF
【问题讨论】:
标签: ios swift uicollectionview uibutton reloaddata