[iOS study] 使用 collection view controller製作照片牆

功能需求:

1 第一頁顯示格子狀(grid)的照片牆。

2 點選照片後,切換到下一頁顯示大張圖片。

教學:

格子狀照片牆:

實作注意事項:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

return cell

更換reuseIdentifier為自己設定的cell identifier(我本次是PhotoCollectionViewCell)

可直接用 "PhotoCollectionViewCell"

或是 "\(PhotoCollectionViewCell.self)" (當cell identifier與class 同名)

然而其實程式有預設

可以直接將"Cell" 改成自己設定的cell identifier

而本次self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 是用不到的,

如果像我使用以下,但是沒有移除上列,將會轉型失敗!

private let reuseIdentifier = "PhotoCollectionViewCell"override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoCollectionViewCellreturn cell}

判斷選取的collectionView的cell,顯示對應的image

使用IBSegueAction

首先要確定使用的xcode版本可以拉取segueAction

將cell拉到顯示單張頁面產生segue

將segue拉到collectionViewController產生@IBSegueAction

在顯示單張頁面設定變數

import UIKitclass OnePhotoViewController: UIViewController {var imageName: String = ""@IBOutlet weak var oneImage: UIImageView!override func viewDidLoad() {super.viewDidLoad()oneImage.image = UIImage(named: imageName)}}

在IBSegueAction傳輸cell的資料

@IBSegueAction func showDetail(_ coder: NSCoder) -> OnePhotoViewController? {let controller = OnePhotoViewController(coder: coder)let cellId = self.collectionView.indexPathsForSelectedItems?.first?.rowcontroller?.imageName = imageNames[cellId!]return controller}

self.collectionView.indexPathsForSelectedItems的資料長相為

[[section, row]]

點選切換畫面:

github:

--

--

Yolanda H.
彼得潘的 Swift iOS / Flutter App 開發教室

悠琅妲之愛梯熙緹推敲推敲潑墨坊 { iOS App | website SEO | Python | Aroma | Zumba | Chinese Poems | Tabletop game }