【问题标题】:Code for UICollectionView in creating a News feed on a mobile appUICollectionView 在移动应用上创建新闻提要的代码
【发布时间】:2017-02-12 12:16:54
【问题描述】:

我是编码初学者,我想学习设计 iOS 移动应用程序。我通过重新创建通过观看 Youtube 构建的应用程序来学习。我目前正在重新创建 Facebook 新闻提要。下面是我学到的自定义代码。我被困在我们构建单元的部分和它们的大小上。具体来说,我收到一个错误: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

【问题讨论】:

    标签: ios swift3 uicollectionview


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      选择一个 Cocoa Touch 类

      选择类名并勾选创建 xib 文件,然后下一步

      终于

      尝试替换这一行:

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

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

      “fileName”是您的 xib 文件名。

      【讨论】:

      • 感谢以上帮助!!我将代码准确地放入并在 AppDelegate.swift 部分得到了错误代码:
      • 它是类 AppDelegate: UIResponder, UIApplicationDelegate {
      • 你有单元格的 .xib 文件吗?
      • 这听起来像是初级的,但我没有。什么是 .xib 文件,为什么需要它?我是按照教程学习的。
      • 本教程基于 2015-2016 年以前版本的 Xcode。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多