【 iOS Swift 】#13–3 可不可飲料訂購APP (CollectionView Header、Navi. Title設定)

續上一集,發現可不可官網有自動輪播的宣傳海報,於是也打算加入APP,成品如下:

加入GIF到CollectionView的Header

先在StoryBoard加入CollectionViewController,並在右側Attributes Inspector中的Accessories打勾Section Header、拉大CollectionView上Header的面積:

放入一個與1920*1080差不多比例的ImageView (393*221)

這時,會發現左側欄多了「Collection Reusable View」

因此,我們還需要再建立一個屬於這個View的File,並設定Class和Identifier,以及拉上ImageView的Outlet:

(注意拉Outlet時,要點選到左側欄的Image View,這樣才可以切換到HeaderCollectionReusableView這段程式碼)

import UIKit

class HeaderCollectionReusableView: UICollectionReusableView {

@IBOutlet weak var bannerImageView: UIImageView!

}

接著,來準備宣傳的海報照片到Asset裡,注意每張照片的檔名需一致,後面加上編號:

再回到HomeCollectionViewController中Delegate的區塊,寫上這個func以實作protocol

// MARK: UICollectionViewDelegate

//設定Header Banner GIF
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {

case UICollectionView.elementKindSectionHeader:

//寫上剛剛建立的HeaderCollectionReusableView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCollectionReusableView", for: indexPath) as! HeaderCollectionReusableView

//設定GIF輪播照片,照片名稱為我們剛剛匯入assets,檔名編號以前的部分,接著輸入稍大的duration來減緩播放速度
headerView.bannerImageView.image = UIImage.animatedImageNamed("banner", duration: 10)

return headerView

default:
fatalError("Unexpected element kind")
}
}

在DataSource區塊設定Section為1:

// MARK: UICollectionViewDataSource

override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

這樣就大功告成拉!

將Navigation Controller的Title變成圖片

再來,我們為APP畫面的頁首加上可不可Logo

首先,找一張尺寸扁扁去背好的可不可Logo加入到assets

(因為動態島很擋的關係,圖片會變很小張)

最後,在HomeCollectionViewController的ViewDidLoad加上:

//設定Navigation Title變成Logo圖片
let navImageView = UIImageView(image: UIImage(named: "logo"))
navImageView.contentMode = .scaleAspectFit
navigationItem.titleView = navImageView

大功告成!

--

--

Yen Lin
彼得潘的 Swift iOS / Flutter App 開發教室

iOS Developer in Taiwan | A person who loves to learn cool stuffs. Check out my website to discover more about me: https://yenlin.webflow.io/