【问题标题】:UICollectionView cannot display customized cell contentUICollectionView 无法显示自定义单元格内容
【发布时间】:2015-12-28 02:31:57
【问题描述】:

我尝试使用 UICollectionView 创建一个虚拟照片应用程序。我的 Xcode 版本是 7.2,Swift 版本是 2.1.1。我按照http://www.raywenderlich.com/78550/beginning-ios-collection-views-swift-part-1 的教程使用Storyboard 构建UI 部分

在 Swift 2.0 中,UICollectionViewDataSource 继承自 UICollectionViewController,我们不需要显式声明这些协议。我为 DataSource 实现了所需的覆盖方法,并在 UICollectionViewControllerviewDidLoad() 中注册了自定义单元格。我在我的单元格中放置了一个测试 Label 以检查它是否有效。不幸的是,标签在我启动应用程序后从未出现。我在下面附上我的一些代码作为参考:

UICollectionViewController

class VacationsCollectionViewController: UICollectionViewController {

    private let reuseIdentifier = "VacationCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(VacationsCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! VacationsCollectionViewCell

        // Configure the cell
        cell.backgroundColor = UIColor.blueColor()
        cell.CellText.text = "Show me the money"

        return cell
    }
}

UICollectionViewCell

class VacationsCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var CellText: UILabel!
}

知道为什么标签从不出现在我的虚拟应用程序中吗?

【问题讨论】:

  • 在您的故事板中,选择您的UICollectionViewCell 并打开属性检查器。确保您已在 Identifier 字段中输入 VacationCell
  • @dfri 是的,标识符的值是VacationCell。不过感谢提醒,这很容易忘记。

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

看起来您拥有所需的一切。问题可能与您的故事板有关。为了安全起见,给标签添加约束,这样它肯定会正确显示。然后,为您的集合视图控制器添加一个扩展,并确保该大小也允许显示标签。至少,这对我有用,而我正是你的情况。

extension OfficesCollectionViewController: UICollectionViewDelegateFlowLayout{
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSize(width: 200, height: 200)
    }
}

【讨论】:

  • 我最终决定用完全相同的逻辑切换到 UITableView,并且成功了。感谢您的回答。
猜你喜欢
  • 2018-08-29
  • 2017-06-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多