ios - swift - "must register a nib or a class for the identifier or connect a prototype cell in a storyboard"

标签 ios swift uicollectionview

我不断收到此错误消息。我已经尝试将其添加到我的代码中:

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/

相关文章:

ios - 无法在 Swift 中显示 map 注释

ios - 如何在具有 dequeueReusableCell 的同时以编程方式设置 tableview 样式以具有副标题?

ios - 如何制作秒表定时器

ios - 应该将UICollectionViewCell子类的contentView.translatesAutoResizingMaskToConstraints设置为 `false`吗?

ios - tableView 中的搜索和复选标记

ios - 在类似于App Store "Description"Cell的UITableViewCell中扩展UITextView

IOS iPad应用程序底部奇怪的白色区域

ios - Swift 中的 CTCallCenter

ios - 带有Tap Gesture Recognizer的UILabel无法正常工作

ios - 对齐 Collection View 单元格以适合每行 3 个