マンガ読書管理アプリの設計メモ(17)
今回は、コレクションビューで漫画を表示するところを書きたいと思います。
1.StoryboardでUI部品をポチポチ配置します。
2.基本的な考え方はTableViewと同じ。お決まりで実装していく
まずはUICollectionViewDelegate,UICollectionViewDataSourceをdelegateしていくことで、実装をViewControllerに記載するようにします。(Storyboardでcollectionviewのdelegate設定をしました)
class ReadedViewController: UIViewController,UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
TableViewでもお決まりのセルの数とセルの内容を実装するメソッドを記述していきます。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let wb = readedBooks{
if wb.isEmpty{
return 0
}
else{
return readedBooks.count
}
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "readedBookCell", for: indexPath) as? ReadedCollectionViewCell else{
return UICollectionViewCell()
}
return cell
}
カスタムセルもこのようなクラスで作っています。
class ReadedCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var bookImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
}
3.レイアウトを整える
今回は横3つのセルを並べたいので、その辺りを調整しています。
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
let widthSize : CGFloat = self.view.bounds.width / 3 - 10
let heightSize : CGFloat = self.view.bounds.height / 4 - 5
layout.itemSize = CGSize(width: widthSize, height: heightSize)
collectionView.collectionViewLayout = layout
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let horizontalSpace : CGFloat = 0
let cellSize : CGFloat = self.view.bounds.width / 3 - horizontalSpace
return CGSize(width: cellSize, height: cellSize)
}
ちょっと乱暴なやり方だったので、iphoneXSではない画面サイズでは多少ずれるかもしれませんが、それはこの後、テストして確認すると割り切りました汗
4.データをセルにセットする。
最後にセルにデータをセットして表示させます。画像データは、登録画面で保存したデータを使用するようにしています。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "readedBookCell", for: indexPath) as? ReadedCollectionViewCell else{
return UICollectionViewCell()
}
let fileName = readedBooks[indexPath.row].imagePath
let documentsPath = NSHomeDirectory() + "/Documents/"
let filePath = documentsPath + fileName
let getBookImage = UIImage(contentsOfFile: filePath)
cell.bookImageView.image = getBookImage
cell.titleLabel.text = readedBooks[indexPath.row].title
return cell
}
これで、一通りの画面ができました!動きは動画に撮ってみましたのでご確認ください。
次は、保守に必須と思われるユーザ統計情報の取得とクラッシュバグの取得ができるように、Firebaseを使うところを説明できればと思います!
また、今回の部分、もしくは今までのところでも良いので、この辺りはもっと詳しく、という話があれば、コメントいただければと思います!
素敵なアプリやサービスが作れるようにひとりで開発を頑張っています。応援してくれると嬉しいです!