我不断收到此错误消息。我已经尝试将其添加到我的代码中:
self.collectionView.register(UICollectionCell.self, forCellReuseIdentifier: "Cell")
但这只会引发另一个错误:
Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'
这是我的代码:
class HomeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var UICollectionView: UICollectionView!
let items = ["0", "1", "2", "3", "4"]
override func viewDidLoad() {
self.UICollectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.mainListLabel.text = items[indexPath.item]
return cell
}
最佳答案
改变
self.collectionView.register(UICollectionCell.self, forCellReuseIdentifier: "Cell")
到
self.collectionView.register(UICollectionViewCell.self, forCellReuseIdentifier: "Cell")
和
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! UICollectionViewCell
CollectionViewCell
代表什么?它是派生类还是什么?
因为您注册了 UICollectionCell
但调用了 CollectionViewCell
?
我希望它有用。
//编辑
最终解决方案:
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var mainListButton: UIButton!
@IBOutlet weak var mainListLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.backgroundColor = UIColor.black
}
}
设置您的自定义 Collection View 类或使用 XIB。
关于ios - swift - "must register a nib or a class for the identifier or connect a prototype cell in a storyboard",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58493225/