質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1182閲覧

CollectionViewCellの部品が表示されない

nishimu

総合スコア26

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2020/06/05 00:55

編集2020/06/05 06:00

前提・実現したいこと

StoryboardにCollectionViewをおき、CollectionViewのセクションごとにcellに表示する内容やcellの大きさを変更して表示する機能を実装したいです
実装中に

CollectionViewCell_D(Sも)のupdateUI

imageView_D.image = interest.featuredImage titile_D.text = interest.title view_D.backgroundColor = interest.color

この部分にに以下のエラーメッセージが発生しました。

発生している問題・エラーメッセージ

unexpectedly found nil while unwrapping an Optional value

該当のソースコード

import UIKit class ViewController_DS: UIViewController, UICollectionViewDelegateFlowLayout,UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! var interests = Interest.fetchInterest() var subCommittees = Subcommittee.fetchSubcommittee() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.red self.collectionView.backgroundColor = UIColor.blue collectionView.register(CollectionViewCell_D.self, forCellWithReuseIdentifier: "CollectionViewCell_D") collectionView.register(CollectionViewCell_S.self, forCellWithReuseIdentifier: "CollectionViewCell_S") let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical } func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView : UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { print("generated (interests.count) d-cells") return interests.count } else{ print("generated (subCommittees.count) s-cells") return subCommittees.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 0 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell_D", for: indexPath) as! CollectionViewCell_D let interest = interests[indexPath.item] cell.interest = interest cell.backgroundColor = UIColor.yellow print("add items to (indexPath.item)") return cell }else{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell_S", for: indexPath) as! CollectionViewCell_S let subCommittee = subCommittees[indexPath.item] cell.subCommittee = subCommittee cell.backgroundColor = UIColor.green print("add items to (indexPath.item)") return cell } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 0 { let cellSize = self.view.bounds.width / 4 print("width: (cellSize)"+"height: 150") return CGSize(width: cellSize, height: 150) }else{ let cellSize : CGFloat = self.view.bounds.width - 16 print("width:(cellSize)"+"height: 150") return CGSize(width: cellSize, height: 250) } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SectionHeader", for: indexPath) as? SectionHeader else { fatalError("Could not find proper header") } if kind == UICollectionView.elementKindSectionHeader { if indexPath.section == 0 { header.sectionLabel?.text = "討論会" }else{ header.sectionLabel?.text = "分科会" } return header } return UICollectionReusableView() } }

↓1つのcollectionViewにCollectionViewCell_DCollectionViewCell_Sを登録して使っておりますが同内容であるため文字数の都合上CollectionViewCell_Dのみ掲載します

swift

1import UIKit 2 3class CollectionViewCell_D: UICollectionViewCell { 4 5 @IBOutlet weak var view_D: UIView! 6 @IBOutlet weak var imageView_D: UIImageView! 7 @IBOutlet weak var titile_D: UILabel! 8 9 var interest: Interest!{ 10 didSet{ 11 print(title_D) 12       // nilが返る 13 self.updateUI() 14 } 15 } 16 func updateUI() { 17 if let interest = interest { 18 imageView_D.image = interest.featuredImage 19 titile_D.text = interest.title 20 view_D.backgroundColor = interest.color 21 }else{ 22 imageView_D.image = nil 23 titile_D.text = nil 24 view_D.backgroundColor = nil 25 } 26 view_D.layer.cornerRadius = 5.0 27 view_D.layer.masksToBounds = true 28 imageView_D.layer.cornerRadius = 5.0 29 imageView_D.layer.masksToBounds = true 30 31 } 32} 33

↓データを扱うクラスはInterestSubcommitteeがありますが同内容であるためInterestのみ掲載させていただきます

import UIKit class Interest { var title = "" var featuredImage: UIImage var color: UIColor init(title: String, featuredImage: UIImage, color: UIColor) { self.title = title self.featuredImage = featuredImage self.color = color } static func fetchInterest() -> [Interest] { return[ Interest(title: "How can we do to stop the war?", featuredImage: UIImage(named: "war")!, color: UIColor(red: 178/255.0, green: 98/255.0, blue: 71/255.0, alpha: 0.6)), Interest(title: "Should we ban zoo?", featuredImage: UIImage(named: "animals")!, color: UIColor(red: 20/255.0, green: 98/255.0, blue: 71/255.0, alpha: 0.6)), Interest(title: "Should we ban wearing the veil?", featuredImage: UIImage(named: "international")!, color: UIColor(red: 178/255.0, green: 98/255.0, blue: 71/255.0, alpha: 0.6)), Interest(title: "Should we legalize all of th gambling?", featuredImage: UIImage(named: "politics")!, color: UIColor(red: 178/255.0, green: 98/255.0, blue: 71/255.0, alpha: 0.6)), Interest(title: "How we reduce green house gas?", featuredImage: UIImage(named: "environment")!, color: UIColor(red: 178/255.0, green: 98/255.0, blue: 71/255.0, alpha: 0.6)) ] } }

自分が考えて実行したこと

エラーメッセージが出たあと
cellの部品ははOutlet接続時にオプショナル型として宣言されているからアンラップしないと利用できないのではないかと考え

imageView_D?.image = interest.featuredImage titile_D?.text = interest.title view_D?.backgroundColor = interest.color

エラーが出たところをにオプショナルチェイニングをしました。すると
イメージ説明
イメージ説明
提示させていただいたコードにあるprint文の出力は正常になされており、cellの数、大きさなどに異常はありませんがcellの部品は表示されていません

本現象の原因、それを解決する方法をご教授願います

私自身、初心者でありますのでオプショナル型の扱いにはあまり慣れておりませんので間違いがありましたらご指摘願います

補足情報(FW/ツールのバージョンなど)

Xcode Version 11.5

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2020/06/05 02:47 編集

collectionViewCell/didSet内で var interest: Interest!{ didSet{ print(titile_D) self.updateUI() } } とした場合に、コンソールにnilと表示されるならば、 CollectionViewCell内の各UIObjectのOutlet接続を再度確認してみてください。 部品自体の配置が正しいかは、背景が透明や白だとわからないので色を付けるなどして、画面に表示されるかを確認してください。
nishimu

2020/06/05 06:03

collectionViewCell/didSet内で var interest: Interest!{ didSet{ print(titile_D) self.updateUI() } } とした場合にコンソールにnilと表示されたので、 CollectionViewCell内の各UIObjectのOutlet接続を再度接続し直しましたが コンソールはnilのままです 部品の配置についてですが色をつけたものを提示させていただきました。 よろしくお願いします
退会済みユーザー

退会済みユーザー

2020/06/05 06:13

黄色がセルの背景だとしたら、ラベルがどこかにあると思うので、ラベルの背景に色をつけてあげるなりして どこに表示してあるか確認してください。 それとともに、outlet接続を見直して、nilではなくUILabelとか表示されるようにしてください。 XIBの作り方(クラスの設定など)は大丈夫でしょうか?
nishimu

2020/06/05 06:46

いろいろな資料を漁っていたら参考になる資料を見つけ、解決にこぎつけました。 ご迷惑をおかけしすみませんでした。
guest

回答1

0

自己解決

カスタムセルの定義の仕方に問題があったようです。
StoryboardでCollectionView_Dを定義していたので

collectionView.register(CollectionView_D.self, forCellWithReuseIdentifier: "CollectionView_D")

は不要でした。こちらを削除すると部品が表示されました。

CollectionView_Sの方はXibファイルの方で定義していたので

collectionView.register(UINib(nibName: "CollectionViewCell_S", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell_S")

を使用して、指定のxibファイルが読み込まれるようにしました。

なぜこうなるのか疑問に思い調べたところ、

collectionView.register(CollectionView_D.self, forCellWithReuseIdentifier: "CollectionView_D")

これはカスタムセルをコードで定義するときに使用するようです。
これを使用しているのにinit(frame: CGRect)の中で何も部品を作成していないのでtitle_Dがnilになったようです。
本現象の解決に参考になったサイト teratail: UIcollectionViewのCustomCellでnil
コードのみでcollectionViewの作成 カスタムセルをコードで定義するには

投稿2020/06/05 06:44

nishimu

総合スコア26

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問