[英]Swift cells are created but don't show up in UICollectionView swift 5
我正在使用自定义集合视图单元格创建集合视图。 因此,我在 storyboard 视图 controller 中创建了集合视图。 问题是我的单元格是在 cellForItemAt 中创建的,但它们根本没有显示,我也尝试过使用默认单元格,但它们也没有显示,当然,我已经尝试了我找到的所有解决方案。 感谢您提前提供帮助!
查看 controller class 相关零件
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
title = set?.name
collectionView!.register(WordCollectionViewCell.self, forCellWithReuseIdentifier: Identifies.WordCollectionViewCellIdentifier)
let buttonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonPressed))
navigationItem.rightBarButtonItem = buttonItem
updateTranslations()
}
hide: false 控制台: true babel: false -->
extension SingleSetViewController : UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(translations.count)
return translations.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifies.WordCollectionViewCellIdentifier, for: indexPath) as! WordCollectionViewCell
cell.translation = translations[indexPath.row]
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
集合视图单元 class
class WordCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var wordLabel: UILabel!
private var showsWord = true
private var _translation : Translation?
var translation : Translation {
set {
_translation = newValue
}
get {
return _translation ?? Translation(word: "", translation: "")
}
}
override func awakeFromNib() {
super.awakeFromNib()
let gestureRecognizer = UITapGestureRecognizer(target: self , action: #selector(flip))
gestureRecognizer.numberOfTapsRequired = 1
self.addGestureRecognizer(gestureRecognizer)
wordLabel.text = _translation?.word
}
@objc private func flip(_ sender: UIGestureRecognizer){
let options : UIView.AnimationOptions = [.transitionFlipFromRight]
UIView.transition(with: self, duration: 0.5, options: options){
if let translation = self._translation {
self.wordLabel.text = self.showsWord ? translation.translation : translation.word
self.showsWord = !self.showsWord
}
}
}
static func nib() -> UINib {
return UINib(nibName: NibNames.WordCollectionViewCellNibName, bundle: nil)
}
}
您的awakeFromNib
方法可能在您设置单元格的translation
属性之前触发。 尝试在翻译的设置器中设置 label 文本:
set {
_translation = newValue
wordLabel?.text = _translation?.word
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.