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

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

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

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

Swift

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

Q&A

解決済

1回答

3695閲覧

CollectionViewのCellにImageViewを表示させる方法(コードのみ, storyboard使わない)

gomugomu

総合スコア6

Xcode

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

Swift

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

0グッド

0クリップ

投稿2020/02/22 11:54

編集2020/02/22 11:55

プログラミング初心者です。

前提・実現したいこと

storyboardを使わずに、CollectionViewの2つ目のsection(画像黄色, section1)cellにimageViewを載せて画像を表示させたいです。
2つのsectionでCollectionViewを構成しています

イメージ説明

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

エラーメッセージは表示されていないのですが何も画像が表示されません。

該当のソースコード

Swift

1 2import UIKit 3 4class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { 5 6 7 let photos = ["photo1", "photo2", "photo3", "photo4", "photo5","photo6"] 8 9 var collectionView: UICollectionView! 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 setCollectionView 14 } 15 16 17 func setCollectionView() { 18 self.collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), collectionViewLayout: UICollectionViewLayout()) 19 collectionView.backgroundColor = .white 20 collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell") 21 collectionView.delegate = self 22 collectionView.dataSource = self 23 let layout = UICollectionViewFlowLayout() 24 layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) 25 collectionView.collectionViewLayout = layout 26 self.view.addSubview(collectionView) 27 } 28 29 30 func numberOfSections(in collectionView: UICollectionView) -> Int { 31 return 2 32 } 33 34 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 35 print("Num: (indexPath.row)") 36 print("SectionNum:(indexPath.section)") 37 } 38 39 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 40 switch section { 41 case 0: 42 return 1 43 case 1: 44 return photos.count 45 default: 46 print("error") 47 return 0 48 } 49 } 50 51 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 52 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) 53 switch indexPath.section { 54 case 0: 55 cell.backgroundColor = .red 56 return cell 57 case 1: 58 cell.backgroundColor = #colorLiteral(red: 1, green: 0.9097372293, blue: 0, alpha: 1) 59 let cellImage = UIImage(named: photos[indexPath.row])! 60 61 return cell 62 default: 63 print("section error") 64 cell.backgroundColor = .white 65 return cell 66 } 67 } 68} 69 70 71 72 73 74 75// MARK:- UICollectionViewDelegateFlowLayout 76 77extension ViewController: UICollectionViewDelegateFlowLayout { 78 79 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 80 81 switch indexPath.section { 82 case 0: 83 let cellwidth1: CGFloat = self.view.frame.size.width 84 let cellheight1: CGFloat = 200 85 return CGSize(width: cellwidth1, height: cellheight1) 86 87 case 1: 88 let horizontalSpace : CGFloat = 10 89 let cellwidth2: CGFloat = self.view.bounds.width / 3 - horizontalSpace 90 let cellheight2: CGFloat = cellwidth2 91 return CGSize(width: cellwidth2, height: cellheight2) 92 93 default: 94 print("section error") 95 return CGSize(width: 0, height: 0) 96 } 97 } 98 99} 100 101

こっちはCollectionViewCellです。

import UIKit class CollectionViewCell: UICollectionViewCell { }

storyboardを使っては実装できるのですが、コードだけでやろうと思うとうまくできません。
教えていただきたいです。

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

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

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

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

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

guest

回答1

0

ベストアンサー

CollectionViewCellと同じサイズのimageViewを表示されるのであれば、CollectionViewCellを下のようにすれば良いでしょう。

swift

1class CollectionViewCell: UICollectionViewCell { 2 let imageView: UIImageView 3 4 required init?(coder: NSCoder) { 5 fatalError("init(coder:) has not been implemented") 6 } 7 8 override init(frame: CGRect) { 9 imageView = .init(frame: .zero) 10 super.init(frame: frame) 11 configureImageView() 12 } 13 // image viewをオートレイアウトで配置する 14 private func configureImageView() { 15 imageView.translatesAutoresizingMaskIntoConstraints = false 16 // content viewの上にimage viewを配置 17 contentView.addSubview(imageView) 18 NSLayoutConstraint.activate([ 19 imageView.topAnchor.constraint(equalTo: contentView.topAnchor), 20 imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), 21 imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), 22 imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) 23 ]) 24 } 25}

使い方:

swift

1let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell 2cell.imageView.image = UIImage(named: "sample-image")

投稿2020/02/22 17:48

tako3

総合スコア71

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

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

gomugomu

2020/02/23 01:45

ありがとうございました!!! cellの参照先をcollectionViewCellにして、上のように書けばいいんですね! 勉強になりました。ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問