【问题标题】:Custom header "fatal error: unexpectedly found nil while unwrapping an Optional value"自定义标头“致命错误:在展开可选值时意外发现 nil”
【发布时间】:2016-01-12 00:54:15
【问题描述】:

这是我对 UICollectionUICollectionViewControllerView 的覆盖函数

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        var view =  UICollectionReusableView()
        if kind == UICollectionElementKindSectionHeader {
            let viewHeader : Header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! Header
            if let userName = viewHeader.userName {
                userName.text = "James Bond"
            }

            view = viewHeader
        }

        return view

    }

问题是每当我尝试运行该应用程序时,在调试之后它总是在该行中弹出错误“致命错误:在展开可选值时意外发现 nil”

let viewHeader : Header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! Header

下面是我的 viewDidLoad 覆盖

override func viewDidLoad() {
super.viewDidLoad()

let layout = UICollectionViewFlowLayout()

collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionView!.delegate = self
collectionView!.dataSource = self

collectionView!.registerClass(SquareCell.self, forCellWithReuseIdentifier: "cell")
collectionView!.registerClass(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")  // UICollectionReusableView
layout.headerReferenceSize = CGSizeMake(self.view.frame.width, 200)

let cellNib = UINib(nibName: "SquareCell", bundle: nil)
collectionView!.registerNib(cellNib, forCellWithReuseIdentifier: "cell")

let headerlNib = UINib(nibName: "HeaderView", bundle: nil)
collectionView!.registerNib(headerlNib, forCellWithReuseIdentifier: "header")


self.view.addSubview(collectionView!)

}

【问题讨论】:

    标签: ios swift header collectionview


    【解决方案1】:

    我发现在我的 Header.swift 类中我不小心添加了不存在的图像名称

    override init(frame: CGRect) {
            super.init(frame: frame)
            self.cover.image = UIImage(named: "cover")
            self.userName.text = "Jame Bond"
        }
    

    所以我删除了图像名称,一切恢复正常:)

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 2016-02-29
      • 2020-09-19
      • 2016-01-08
      相关资源
      最近更新 更多