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

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

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

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

Q&A

0回答

791閲覧

UICollectionViewでカスタムセルをxibで作成するが、セルが表示されない

konakizzi_mk

総合スコア21

Swift

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

0グッド

0クリップ

投稿2021/04/12 08:40

編集2021/04/13 09:44

##実現したいこと
UICollectionViewのセルをxibを使用したカスタムセルで実装したい。
以下のようにソースを書いたが、セル(今回の場合画像)が表示されず何が不足しているか分からないので、ご教示いただきたいです。

##ソースコード

Swift

1import UIKit 2import DKImagePickerController 3 4class PictureViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate { 5 6 var images: [UIImage] = [] 7 8 9 @IBOutlet weak var collectionView: UICollectionView! 10 11 12 override func viewDidLoad() { 13 super.viewDidLoad() 14 // XIBの呼び出し 15 self.loadNib() 16 setup() 17 addLongTapGesture() 18 19 } 20 @IBAction func tapButton(_ sender: Any) { 21 let pickerController = DKImagePickerController() 22 pickerController.maxSelectableCount = 4 - (images.count) 23 pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in 24 for asset in assets { 25 if asset.type == .photo { 26 asset.fetchFullScreenImage(completeBlock: { image, info in 27 guard let image = image else { 28 return 29 } 30 images.append(image) 31 self.collectionView.reloadData() 32 }) 33 } 34 } 35 } 36 present(pickerController, animated: true, completion: nil) 37 } 38 39 // 画面で呼び出すXIBの設定 40 private func loadNib() { 41 let nib = UINib(nibName: "PictureCell", bundle: nil) 42 collectionView.register(nib, forCellWithReuseIdentifier: "PictureCell") 43 } 44 //セルのレイアウト 45 private func setup(){ 46 let layout = UICollectionViewFlowLayout() 47 //セクションの上下左右の位置(一旦仮) 48 layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5) 49 collectionView.collectionViewLayout = layout 50 //Cellの幅と高さサイズ(一旦仮) 51 layout.itemSize = CGSize(width: 220, height: 220) 52 collectionView.alwaysBounceHorizontal = true 53 } 54 55 func addLongTapGesture() { 56 let longTapGesture = UILongPressGestureRecognizer(target:self,action:#selector(longTap(gesture:))) 57 collectionView.addGestureRecognizer(longTapGesture) 58 } 59 60 @objc func longTap(gesture:UILongPressGestureRecognizer){ 61 print("ロングタップ成功") 62 switch gesture.state{ 63 //ロングタップの開始時 64 case.began: 65 guard 66 let selectedIndexPath = collectionView.indexPathForItem(at:gesture.location(in:collectionView))else{ 67 break 68 } 69 collectionView.beginInteractiveMovementForItem(at:selectedIndexPath) 70 //セルの移動中 71 case.changed: 72 collectionView.updateInteractiveMovementTargetPosition(gesture.location(in:gesture.view)) 73 //セルの移動完了時 74 case.ended: 75 collectionView.endInteractiveMovement() 76 default: 77 collectionView.cancelInteractiveMovement() 78 } 79 } 80 81 82 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 83 return images.count 84 } 85 86 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 87 88 var cell: UICollectionViewCell? 89 var imageView: UIImageView? 90 91 cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PictureCell", for: indexPath)as! PictureCell 92 93 //表示 94 if let imageView = imageView { 95 imageView.image = images[indexPath.row] 96 } 97 return cell! 98 } 99 100 //セルの並び替えを可とする 101 func collectionView(_ collectionView:UICollectionView, canMoveItemAt indexPath:IndexPath)-> Bool { 102 return true 103 } 104 //移動したときの挙動 105 func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { 106 reorderCells(sourceIndex: sourceIndexPath.item, destinationIndex: destinationIndexPath.item) 107 } 108 109 // MARK: - PRIVATE METHODS 110 111 /// セルの移動 112 /// 113 /// - Parameters: 114 /// - sourceIndex: 移動元の位置 115 /// - destinationIndex: 移動先の位置 116 private func reorderCells(sourceIndex: Int, destinationIndex: Int) { 117 //画像の入れ替え 118 let image = images.remove(at: sourceIndex) 119 images.insert(image, at: destinationIndex) 120 } 121} 122

##確認したこと

  • PictureCell.xibのclassにPictureCell.swiftを接続していること。
  • PictureCell.xibのidentifierにPictureCellを設定していること。
  • PictureViewControllerのcollectionviewにdatasouceを接続していること。

イメージ説明
イメージ説明

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

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

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

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

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

hoshi-takanori

2021/04/12 08:58

cellForItemAt で cell に画像をセットしてないように見えますが…。
tomato879241

2021/04/12 22:41

xibをcellForItemAtでloadしてみてください。
konakizzi_mk

2021/04/13 08:29

cellForItemAtで cell に画像をセットしましたが、表示されませんでした・・・ (以下では画像セットされないでしょうか?) cell.imageView.image = images[indexPath.row] またxibをcellForItemAtでloadしてみましたが、表示されませんでした・・・ 画像選択まではいけるのですが何が足りていないのかご教示いただけますと幸いですmm
hoshi-takanori

2021/04/13 09:34

xib の load (というか、collectionView への register) は一度すれば充分なので、viewDidLoad() から loadNib() を呼び出してるので大丈夫です。 もしかして、cell.imageView.image = images[indexPath.row] を if 文の中に書いてませんか?
konakizzi_mk

2021/04/13 09:51

if文は削除し、cell.imageView.image = images[indexPath.row]を書きましたが、画像が表示されません。。 cellForItemAtの中は以下のみ記載に修正しました。 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PictureCell", for: indexPath)as! PictureCell cell.imageView.image = images[indexPath.row] return cell
hoshi-takanori

2021/04/13 10:43

うーん、それで良さそうに見えるというか、手元で試したら表示されましたけど…。 PictureCell のクラス定義はどうなってますか?
konakizzi_mk

2021/04/13 11:15

PictureCell.xibのcustum classにはPictureCellが入っています。 初めてxibを使ったので、もしかしたら接続がうまくいっていないのかもしれないです???? また1から作成してみようと思います。。。
hoshi-takanori

2021/04/13 11:18

PictureCell.swift の内容をお聞きしたかったんですが…。ちなみに自分は class PictureCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! } として動きました。もちろん imageView の outlet 接続もお忘れなく。
konakizzi_mk

2021/04/13 11:24

PictureCell.swiftの内容は全く同じ記述をしております。 imageViewのoutlet接続がFile'sOwnerになっていたので、PictureCellにしたら画像表示されました! お手数おかけしました、ありがとうございます!!!
konakizzi_mk

2021/04/13 11:25

outlet接続がFile'sOwnerとPictureCellで何が変わってくるのか調べていきたいと思いますm(__)m
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問