Reputation: 3
I am getting an error when I use storyboard?.instantiate
. It's giving me this error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
and this is my code:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "SelectedViewController")
as? SelectedViewController
vc?.name = imgArr[indexPath.row]
self.navigationController?.pushViewController(vc!, animated: true)
}
and I am already using the identifier ID
in this photo:
Please anyone can help me in this issue.
Upvotes: 0
Views: 719
Reputation: 55
try this below code:
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vcTitles = storyBoard.instantiateViewController(withIdentifier: "vcTitles") as! VCTitlesViewController
self.navigationController?.pushViewController(vcTitles, animated: true)
Upvotes: 0
Reputation: 1374
is SelectedViewController in the same storyboard of the collection view's view controller?
I always prefer to unwrap optionals with a guard or if let to avoid crashes like this. You can use:
guard let viewController = storyboard?.instantiateViewController(withIdentifier: "SelectedViewController") as? SelectedViewController else { "return error here if wanted" return }
viewController.name = imgArr[indexPath.row]
self.navigationController?.pushViewController(viewController, animated: true)
Upvotes: 0
Reputation: 100503
Move the mouse over the class field in IB , then click enter , module check must be ticked , and verify you correctly set storyboard identifier
Upvotes: 1