【问题标题】:Swift CollectionView stopped displaying after adding section header添加节标题后,Swift CollectionView 停止显示
【发布时间】:2016-04-28 00:57:54
【问题描述】:

我创建了一个简单的 collectionView 并将单元格设置为显示每个单元格在单击时进入的屏幕预览。这一切都很好,所以我将继续为每个部分添加标题。

但是,问题来了……

当我将这些部分添加到代码中时,它会导致 collectionView 消失(或者至少除了白屏之外它不显示任何其他内容)

这是我添加(或修改)的代码,如果发布的代码不够,请告诉我,我会发布更多...

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        let sectionHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionHeader", forIndexPath: indexPath) as! SectionHeaderView
        if let title = papersDataSource.titleForSectionAtIndexPath(indexPath) {
            sectionHeaderView.title = title
        }
        return sectionHeaderView
    }

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return papersDataSource.numberOfSections
    }

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return papersDataSource.numberOfPapersInSection(section)
    }

我设置了一个 UICollectionReusableView 的子类,它具有以下代码...

import UIKit

class SectionHeaderView: UICollectionReusableView {

    @IBOutlet weak var titleLabel: UILabel!

    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
}

一切正常,但显示完全空白。

有什么想法吗?

【问题讨论】:

  • 阅读苹果文档,看来你必须重写这个UICollectionViewLayout 方法:layoutAttributesForSupplementaryViewOfKind:atIndexPath: 。我认为该方法应该返回:.SupplementaryView

标签: swift header uicollectionview uicollectionreusableview


【解决方案1】:

在确定上面发布的所有代码都是正确的之后,我决定更好地查看设置和加载所有数据的 dataSource 文件。在四处寻找时,我发现了导致问题的原因,并且是将数据加载到磁盘的方法...

  private func loadPapersFromDisk() -> [Paper] {
    sections.removeAll(keepCapacity: false)
    if let path = NSBundle.mainBundle().pathForResource("Papers", ofType: "plist") {
      if let dictArray = NSArray(contentsOfFile: path) {
        var papers: [Paper] = []
        for item in dictArray {
          if let dict = item as? NSDictionary {
            let caption = dict["caption"] as! String
            let imageName = dict["imageName"] as! String
            let section = dict["section"] as! String
            let index = dict["index"] as! Int
            let paper = Paper(caption: caption, imageName: imageName, section: section, index: index)
            if !sections.contains(section) {
              sections.append(section)
            }
            papers.append(paper)
          }
        }
        return papers
      }
    }
    return []
  }

具体来说,问题出在某个部分的附加论文中。这些部分必须先打开包装,然后才能看起来像......

if sections.contains(section) {
  sections.append(section)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2018-12-17
    • 2017-11-21
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多