CollectionView 致命错误:在展开可选值时意外发现 nil
Posted
技术标签:
【中文标题】CollectionView 致命错误:在展开可选值时意外发现 nil【英文标题】:CollectionView fatal error: unexpectedly found nil while unwrapping an Optional value 【发布时间】:2015-05-15 00:34:44 【问题描述】:我正在尝试在视图确实加载方法中定义的数组中添加一些图像的集合视图。该应用程序构建并运行良好,但是当我导航到名为“投资组合”的特定部分时,应用程序崩溃了,在控制台中给了我这个。
致命错误:在展开可选值时意外发现 nil
谁能从下面的代码中弄清楚发生了什么?我尝试将问题包装在 if 语句中,以防止它崩溃,但图像根本不会显示。如果我只是定义一个 UIBackgroundColor 它应该像它一样工作。
import UIKit
class PortfolioView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource
var array:[String] = []
override func viewDidLoad()
array = ["PortImage1","PortImage2","PortImage3","PortImage4","PortImage5","PortImage6","PortImage7"]
super.viewDidLoad()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return array.count
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(named: array[indexPath.row])
cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2
cell.imageView.clipsToBounds = true
cell.imageView.layer.borderWidth = 2.0
cell.imageView.layer.borderColor = UIColor.whiteColor().CGColor
return cell
【问题讨论】:
但是你不愿意告诉我们哪个是崩溃线? 就是这样。我不知道是什么导致文件崩溃。感谢投反对票的好先生! 【参考方案1】:从表面上看,只是猜测,因为您没有提供 任何 的相关信息,看来您已经定义了一个具有 imageView
属性的类 CollectionViewCell,但是您未能通过插座将情节提要/笔尖中的任何图像视图连接到imageView
属性。因此,在加载时,您的 imageView
属性为零。
【讨论】:
奇怪的是我已经把它连接起来了,但 Xcode 一定不能识别它。我去重新建立连接并且它有效。谢谢【参考方案2】:在您的情况下,单元格无法找到 imageView 并崩溃,因为它发现它为零。 在情节提要中为您的 imageView 提供标签说“100”。 然后在将单元格出列后将以下行添加到您的代码中,如下所示 :-
let imageView = cell.viewWithTag(100) as! UIImageView
imageView.image = UIImage(named: array[indexPath.item])
【讨论】:
以上是关于CollectionView 致命错误:在展开可选值时意外发现 nil的主要内容,如果未能解决你的问题,请参考以下文章
SWIFT 致命错误:在展开可选值 (lldb) 时意外发现 nil