#32 Draggable Flow Layout Photo Wall with Search Bar (Unsplash API)

UISearchBarDelegate / Result Type / NSCache / UIBackgroundConfiguration

Ethan
彼得潘的 Swift iOS / Flutter App 開發教室
10 min readOct 19, 2021

--

Demo

Collection View Flow Layout 設定關鍵

除了用上篇文 #31 Display Different Custom Cells in a Table View (Programmatically) 介紹的 UICollectionViewDelegateFlowLayout 協定方法設定 collection flow layout 外,也可以像下述直接設定 flowLayout 的 itemSize / minimumInteritemSpacing / minimumLineSpacing 屬性。

這邊 width = floor[(螢幕寬-直行分隔線數*直行分隔線寬)÷照片直行數]。

可抓取放下的 Collection View 設定關鍵

搜尋功能:抓 apiResults

這邊還不需要用到 searchResultsController。

ViewController 遵從 UISearchBarDelegate 協定。按下搜尋鍵後,會執行下面方法:

再來的小技巧是將輸入字串的頭尾空白都去掉,內部所有空白也去掉,也確保輸入值非空字串。修正後的字串取為 query。

再來將 query 送進 fetchPhotos 函式,用到了 Result type 的技巧。若成功則回傳 Result 的 success case,附帶 [APIResult] 型別資料;若失敗則回傳 Result 的 failure case,附帶 NetworkError 型別資料。

NetworkHelper class

抓圖片與顯示

注意傳給 fetchImage 函式的參數 url 是 URL 型別用到 NSCache 儲存或取得 NSURL 和 UIImage 型別 Key-value 資料

若成功抓圖則回傳 Result 的 success case,附帶 UIImage 型別資料;若失敗則回傳 Result 的 failure case,附帶 NetworkError 型別資料。

顯示圖片用到 iOS 15 推出的 UIBackgroundConfiguration:

--

--