やりたいこと
コレクションビューで画像と画像名をタイル状に表示したいです。
やったこと
[iPhone] UICollectionView で マス目表示
リンク先の手順を参考に作業しました。
困っていること
ストーリーボードのCell Sizeが適応されていてViewController側で設定したCellのサイズが反映されません。
どのようにしたら反映させられますでしょうか?よろしくお願いします。
// CatalogViewController.swift func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let horizontalSpace: CGFloat = 2 // 端末のサイズを2等分して余白分を確保 let cellSize: CGFloat = self.view.bounds.width / 2 - horizontalSpace return CGSize(width: cellSize, height: cellSize) }
コード
swift
1// CatalogViewController.swift 2 3import UIKit 4 5class CatalogViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { 6 7 // サムネイル画像の名前 8 let photos = ["photo1", "photo2", "photo3"] 9 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 } 13 14 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 15 16 // 識別子("ProductCell")によって特定された再利用可能なセルオブジェクトを返します 17 let productCell: UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) 18 19 // 指定された値とタグが一致するビューを取得、UIImageViewにダウンキャストしてimageViewに代入 20 let imageView = productCell.contentView.viewWithTag(1) as! UIImageView 21 // indexPath.rowはセル番号?行のこと 22 // 画像オブジェクトを生成してproductImageに代入、imageViewのimageに代入 23 let productImage = UIImage(named: photos[indexPath.row]) 24 imageView.image = productImage 25 26 let label = productCell.contentView.viewWithTag(2) as! UILabel 27 label.text = photos[indexPath.row] 28 label.textColor = UIColor.blue 29 30 return productCell 31 } 32 33 // セクションの数を設定 34 func numberOfSections(in collectionView: UICollectionView) -> Int { 35 return 1 36 } 37 38 // セルの数を設定、photosの要素数をreturn 39 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 40 return photos.count 41 } 42 43 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 44 45 let horizontalSpace: CGFloat = 2 46 47 // 端末のサイズを2等分して余白分を確保 48 let cellSize: CGFloat = self.view.bounds.width / 2 - horizontalSpace 49 50 return CGSize(width: cellSize, height: cellSize) 51 } 52 53 override func didReceiveMemoryWarning() { 54 super.didReceiveMemoryWarning() 55 } 56} 57
回答1件
あなたの回答
tips
プレビュー