来自xib文件的UICollectionViewCell未显示在UICollectionView中

时间:2017-07-10 20:39:45

标签: ios swift xcode uicollectionview uicollectionviewcell

我有一个包含标签和UICollectionView的自定义xib文件。我有一个第二个xib文件,用于集合视图的单元格,其自定义子类为UICollectionViewCell

父xib文件的所有者如下所示 -

import UIKit

class PackageSizePickerVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {


    @IBOutlet weak var collection: UICollectionView!


    let sizes: [PackageSize] = {
        let small = PackageSize(title: "Small", imageName: "S")
        let medium = PackageSize(title: "Medium", imageName: "M")
        let large = PackageSize(title: "Large", imageName: "L")
        let extralarge = PackageSize(title: "Extra Large", imageName: "XL")
        return [small, medium, large, extralarge]
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        collection.delegate = self
        collection.dataSource = self

        collection.register(UINib(nibName: "SizesCell", bundle: nil), forCellWithReuseIdentifier: "Sizecell") //register with nib

    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sizes.count
    }

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


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collection.dequeueReusableCell(withReuseIdentifier: "Sizecell", for: indexPath) as? SizesCell {
            let size = sizes[indexPath.row]
            cell.image = size.imageName
            cell.title = size.title
            return cell
        }else{
            return UICollectionViewCell()
        }
    }
}

enter image description here

UICollectionViewCell xib文件名为SizesCell.xib,类文件为SizesCell.swift,SizesCell类中的代码如下所示:

import UIKit

class SizesCell: UICollectionViewCell {

    @IBOutlet weak var sizeImage: UIImageView!
    @IBOutlet weak var sizeLabel: UILabel!

    var image: String!
    var title: String!

    override init(frame: CGRect) {
        super.init(frame: frame)
        sizeImage.image = UIImage(named: image)
        sizeLabel.text = title
    }

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

}

enter image description here enter image description here

enter image description here

其中PackageSize是结构为

struct PackageSize {
    let title: String
    let imageName: String
}

现在我遇到的问题是,单元格只是无法加载到父xib文件的集合视图中,而我根本无法找出initUICollectionViewCell的原因。 1}}类根本没有被调用。我也尝试过awakeFromNib(),但这也没有用。文件所有者,自定义类等都在IB中正确设置。我在这里缺少什么?

0 个答案:

没有答案