UICollectionViewController不显示自定义UICollectionViewCell的子视图

时间:2015-05-28 15:55:23

标签: ios iphone swift uicollectionview uicollectionviewcell

我打算在集合视图中使用自定义单元格概述产品。我已经设置了所有内容,没有任何错误,但不知何故,单元格的内容不会显示出来。

我有

  • 创建了UICollectionViewCell的子类
  • 在故事板中添加了所有子视图,并将它们作为IBOutlets连接到我的班级
  • 使用self.collectionView!.registerClass(ProductCell.self, forCellWithReuseIdentifier: reuseIdentifier)
  • 注册了自定义单元格
  • 检查了数据源,没有错误。这是numberOfItemsInSection:
 override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var items: Int = 0
        if (section == 0) {
            if (currentCategory == nil) {
                items = sharedStore.categories.count
            } else {
                items = currentCategory.categories.count
            }
        } else if (section == 1) {
            if (currentCategory == nil) {
                items = sharedStore.products.count
            } else {
                items = currentCategory.items.count
            }
        }
        return items
    }
  • 设置cellForItemAtIndexPath:
 override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ProductCell

        cell.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.05)
        cell.layer.cornerRadius = 5

        //initialize shit
        cell.titleLabel = UILabel()
        cell.priceLabel = UILabel()

        if(indexPath.section == 0) {
            let current: Category!

            //get model object
            if(currentCategory == nil) {
                if(sharedStore.categories.count > 0) {
                    current = sharedStore.categories[indexPath.row] as! Category
                } else {
                    current = nil
                }
            } else {
                if(currentCategory.categories.count > 0 ) {
                    current = currentCategory.categories[indexPath.row] as! Category
                } else {
                    current = nil
                }
            }

            cell.itemImage = UIImageView(image: UIImage(named: "folderImage.png"))
            cell.itemImage.hidden = false
            cell.titleLabel.text = current.title as String
            cell.priceLabel.hidden = true
        }
 return cell
 }

该单元格为空。没有图像,没有标题,也没有价格标签。 我知道数据源工作正常,因为当我添加产品时,它会显示一个新的单元格。

有关如何将我的物品放入牢房的任何建议?

任何帮助都将受到高度赞赏:)

1 个答案:

答案 0 :(得分:-3)

我想通了:出于某种原因,当您将子视图添加到故事板中的自定义UICollectionViewcell时,它在运行时不会自动将它们添加到单元格中。因此,您必须对该单元格的所有属性执行cell.addSubview(subview),在自定义单元格类或cellForItemAtIndex中执行以下操作。

相关问题