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

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

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

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

Xcode

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

Swift

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

iPhone

iPhoneとは、アップル社が開発・販売しているスマートフォンです。 同社のデジタルオーディオプレーヤーiPodの機能、電話機能、インターネットやメールなどのWeb通信機能の3つをドッキングした機器です。

Q&A

解決済

1回答

1518閲覧

【Swift】CollectionViewを選択した時、imageviewの色合いを変えたい

pi.chan_san

総合スコア3

iOS

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

Xcode

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

Swift

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

iPhone

iPhoneとは、アップル社が開発・販売しているスマートフォンです。 同社のデジタルオーディオプレーヤーiPodの機能、電話機能、インターネットやメールなどのWeb通信機能の3つをドッキングした機器です。

0グッド

0クリップ

投稿2021/04/02 04:33

編集2021/04/02 21:50

前提・実現したいこと

現在swiftでcollectionviewに画像やテキストを設置し、そのcollectionviewを選択した時、画像の色合いを変えるというコードを作っています。
画像の色合いを変えるのにはCIFilterを使用しています。
collectionviewのあるページに遷移しようとして際に以下のエラーメッセージが発生しました。

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

this class is not key value coding-compliant for the key inputContrast.

該当のソースコード

swift

1import UIKit 2 3class CollectionViewCell: UICollectionViewCell { 4 5 private let chooseLabel: UILabel = { 6 let label = UILabel() 7 label.frame = CGRect(x: 0, y: (screenSize.width-50) / 2, width: (screenSize.width-50) / 2, height: 50) 8// label.textColor = UIColor.gray 9 label.textAlignment = .center 10 return label 11 }() 12 13 private let chooseImage: UIImageView = { 14 let image = UIImageView() 15 image.frame = CGRect(x: 0, y: 0, width: (screenSize.width-50) / 2, height: (screenSize.width-50) / 2) 16 return image 17 }() 18 19 private var ciFilter: CIFilter! 20 var imagePath: String = "hoge" 21 22 dynamic var filteredImage: CIImage? = nil 23 24 override init(frame: CGRect) { 25 super.init(frame: frame) 26 setup() 27 // CIFilterの生成 28 ciFilter = CIFilter(name: "CITemperatureAndTint") 29 } 30 31 required init?(coder aDecoder: NSCoder) { 32 fatalError("init(coder:) has not been implemented") 33 } 34 35 36 private func setup() { 37 38 chooseImage.contentMode = .scaleAspectFill 39 chooseImage.clipsToBounds = true 40 contentView.addSubview(chooseLabel) 41 contentView.addSubview(chooseImage) 42 } 43 44 func setupContents(textName: String, imagepath: String) { 45 chooseLabel.text = textName 46 chooseImage.image = UIImage(named: imagepath) 47 let ciImage = chooseImage.image?.ciImage ?? CIImage(image: chooseImage.image!) 48 // 入力画像の設定 49 ciFilter.setValue(ciImage, forKey: kCIInputImageKey) 50 ciFilter.setValue(70, forKey: kCIInputContrastKey) 51 filteredImage = ciFilter.outputImage 52 self.imagePath = imagepath 53 } 54 55 func onTapped(_ filterOn: Bool) { 56 if filterOn == true { 57 chooseImage.image = UIImage(ciImage: filteredImage!) 58 } else { 59 chooseImage.image = UIImage(named: imagePath) 60 } 61 } 62}

Swift

1import UIKit 2 3class MainChooseViewController: UIViewController { 4 5//以下のdictionaryは、collectionviewの中身です 6 var recipeList = ["pasta", "omelette rice", "Yellowtail teriyaki", "scallop cooked rice"] 7 var imageList = ["3ac4720cd39fcb7bc418a360734f4769f593c4e0.jpg", "26fb8d743b3e3e7645a4a947f4db74cb.jpg.webp", "i=https%3A%2F%2Fimage.excite.co.jp%2Fjp%2Ferecipe%2Frecipe%2F0%2F0%2F0075f14723f0ca3a9bcf5062871299b4%2F8e6ae4fb7223467b78bfd88ab8559dc0.jpeg&small=400&quality=100&type=jpeg.jpeg", "recipe.jpg"] 8 private let collectionView: UICollectionView = { 9 10 //セルのレイアウト設計 11 let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 12 13 //各々の設計に合わせて調整 14 layout.scrollDirection = .vertical 15 layout.minimumInteritemSpacing = 0 16 layout.minimumLineSpacing = 10 17 18 let collectionView = UICollectionView( frame: CGRect(x: 20, y: 100, width: screenSize.width - 40, height: screenSize.height/2 + 50 ), collectionViewLayout: layout) 19 collectionView.backgroundColor = UIColor.white 20 //セルの登録 21 collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell") 22 return collectionView 23 }() 24 25 override func viewDidLoad() { 26 super.viewDidLoad() 27 self.pageScrollView.delegate = self 28 29 //生成したcollectionViewのdataSourceとdelegteを紐づける 30 collectionView.dataSource = self 31 collectionView.delegate = self 32 33 34 view.addSubview(collectionView) 35 mainView.addSubview(collectionView) 36 37 if pageControl.currentPage == 0 { 38 backButton.isHidden = true 39 } else { 40 backButton.isHidden = false 41 } 42 43 if pageControl.currentPage == 2 { 44 nextButton.isHidden = true 45 } 46 47 } 48 49 50 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 51 super.touchesBegan(touches, with: event) 52 53 self.view.endEditing(true) 54 } 55  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 56 57 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell 58 59 let imagepath = imageList[indexPath.item] 60 let cellText = recipeList[indexPath.item] 61 cell.setupContents(textName: cellText, imagepath: imagepath) 62 63 return cell 64 } 65 66//イベントの設定 67extension MainChooseViewController: UICollectionViewDelegate { 68 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 69 print("callされました") 70 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell 71 cell.onTapped(true) 72 } 73} 74 75//cellのサイズの設定 76extension MainChooseViewController: UICollectionViewDelegateFlowLayout { 77 78 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 79 80 return CGSize(width: (screenSize.width-50) / 2, height: (screenSize.width-50)/2 + 50) 81 } 82 83}

試したこと

試しに色々なところをコメントアウトしてみたのですが、
ciFilter.setValue(70, forKey: kCIInputContrastKey)
の部分をコメントアウトしてみた時、画面遷移はすることができるようになりました。
その時、collectionViewを試しに選択してみたら、
cellクラス、onTapped関数内の
chooseImage.image = UIImage(ciImage: filteredImage!)の部分に

Fatal error: Unexpectedly found nil while unwrapping an Optional value
このようなエラーが出ました。printの"callされました"は呼び出されていて、このエラーの原因はなんとなく想像できます。
情報の一つとして参考にしていただけたら嬉しいです。
わかる方、お力添えよろしくお願いします。

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

Swift5
Mac OS 11.2.2
Xcode 12.4

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

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

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

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

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

hoshi-takanori

2021/04/02 06:31

didSelectItemAt の中で dequeueReusableCell してはいけないというか、cellForItemAt 以外でしても意味がありません。ソースが断片的でよく分かりませんが、基本的な collection view の扱いに問題がありそうな気がします。
pi.chan_san

2021/04/02 13:46

ご指摘ありがとうございます!私の考えでは、セルを選択した時にonTapped関数を呼び出したいなと思い、didSelectItemAt 関数を設置したつもりです。 dequeReuseCell は cellForItemAt でしか使えないのですね!知りませんでした。。そうするとdidSelectItemAt内の書き方はどうなるのでしょうか?初歩的なことですが、教えていただけると嬉しいです。 あと、よくみたら足りない部分ありました。毎度情報が足らず、申し訳ございません。
guest

回答1

0

ベストアンサー

dequeueReusableCell は、事前に register した xib ファイルなどに基づいて新しいセルを生成 (または再利用) するメソッドで、これを呼び出すのは基本的に cellForItemAt だけです。
didSelectItemAt でやりたいのは既に生成されて画面に表示されているセルを取得することで、そのためには cellForItem(at:) を使うと良いでしょう。

swift

1extension MainChooseViewController: UICollectionViewDelegate { 2 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 3 if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell { 4 cell.onTapped(true) 5 } 6 } 7 8 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { 9 if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell { 10 cell.onTapped(false) 11 } 12 } 13}

投稿2021/04/03 10:15

編集2021/04/03 10:39
hoshi-takanori

総合スコア7895

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

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

pi.chan_san

2021/04/03 11:51

なるほど!解決しました。ご丁寧に回答いただき、ありがとうございました。またよろしくお願いいたします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問