【发布时间】:2022-07-07 18:23:13
【问题描述】:
面对这样的焦虑。注册到单元格并导航到 DetailViewController 时,出现以下错误:“错误流 1:致命错误:在隐式扩展可选值时意外发现 nil”并且应用程序崩溃。
视图控制器
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? UICollectionViewCell,
let indexPath = self.collectionView.indexPath(for: cell) {
let vc = segue.destination as! DetailViewController //Cast with your DestinationController
//Now simply set the title property of vc
vc.titlePost.text = posts[indexPath.row].title // error Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
vc.previewPost.text = posts[indexPath.row].preview_text
}
}
DetailViewController
class DetailViewController: UIViewController {
private var fullPost: Detail?
@IBOutlet weak var titlePost: UILabel!
@IBOutlet weak var previewPost: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
postView()
}
private func postView() {
titlePost.text = fullPost?.title
titlePost.text = fullPost?.text
}
}
如何解决这样的问题?
【问题讨论】:
-
let vc = segue.destination as! DetailViewController这里vc已经初始化,但是它的视图(以及它的所有子视图,比如你的IBOutlettitlePost)还没有被加载。所以vc.titlePost是nil。既然你已经有一个fullPost变量,不要将其设为私有,并将其设置为pepare(for:sender:):vc.fullPost = posts[indexPath.row],然后在你的viewDidLoad()中你已经设置了标签值。