用于在移动应用上创建新闻Feed的UICollectionView代码

时间:2017-02-12 12:16:55

标签: ios swift3 uicollectionview

我是编码的初学者,我想学习设计iOS移动应用程序。我正在通过重新创建通过观看Youtube而构建的应用程序来学习。我目前正在重新创建Facebook新闻Feed。以下是我学到的自定义代码。我被困在我们构建细胞的部分和它们的大小上。具体来说,我收到一个错误:collectionView?.registerClass(FeedCell.self,forCellWithReuseIdentifier:cellId)。在以前的Swift版本中,这似乎是可行的陈述,但不是3.0。感谢任何人的帮助!

以下是代码:

import UIKit

let cellId = "cellId"

class FeedController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Facebook Feed"


    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)

    collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: cellId)


}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
}

func collectionView(_collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 50)



}
}

class FeedCell: UICollectionViewCell {

    override init(frame: CGRect){
        super.init(frame: frame)

        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupViews()  {

    backgroundColor = UIColor.white

2 个答案:

答案 0 :(得分:5)

在创建自定义collectionView单元格时,必须使用“collectionView.registerNib”而不是collectionView.registerClass。

collectionView.registerNib(UINib(nibName: "Your Nib Name", bundle: nil), forCellWithReuseIdentifier: "Your Cell Identifier")

答案 1 :(得分:0)

要添加单元格,请右键单击要添加文件的位置:

enter image description here

选择Cocoa Touch类

enter image description here

选择班级名称,然后选中创建xib文件,然后再创建

enter image description here

<强>最后

尝试替换此行:

collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: cellId)

collectionView?.register(UINib(nibName: "fileName", bundle: nil), forCellWithReuseIdentifier: cellId)

“fileName”是你的xib文件名。