前提
CollectionViewのcellにImageを配置したいです。
imageViewにTag2を設定しているのですが、画面遷移の際にクラッシュしてしまう。
エラーはviewWithTagのところで出ています。
Tagの紐付け(?)ができていなくnilになっているのかと思うのですが、storyboardを見てもTagは設定されているので、どこを直したらいいかわかりません。
発生している問題・エラーメッセージ
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
該当のソースコード
swift
1class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { 2@IBOutlet var collectionView: UICollectionView! 3 let Items = ["item1", "item2", "item3" ] 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 collectionView.delegate = self 8 collectionView.dataSource = self 9 } 10 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 11 return Items.count // 表示するセルの数 12 } 13 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 14 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) 15 cell.backgroundColor = .white 16 let Imagecell = cell.contentView.viewWithTag(2) as! UIImageView 17//エラーメッセージ viewWithTag 18 Imagecell.image = UIImage(named: Items[indexPath.row]) 19 20 return cell 21 } 22 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 23 let horizontalSpace : CGFloat = 20 24 //self.view.bounds.widthデバイスのサイズ 25 let cellSize : CGFloat = self.collectionView.bounds.width / 6 - horizontalSpace*2 26 return CGSize(width: cellSize, height: cellSize) 27 } 28} 29 30 31 32 33
追記
dump(cell.contentView.viewWithTag(2)) →nil
contentViewにTagが設定されていないか確認 →Tag0
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

回答1件
あなたの回答
tips
プレビュー