ScrollViewDelegate — 分頁與縮放

UIScrollViewDelegate, Stack View, Page Control, viewForZooming

--

成品:選了這季比較喜歡的日劇

▲通常照片瀏覽用 collection view / UIPageViewController 效果較好
▲模擬器縮放請按 option + 滑鼠拉
▲心不靜,這作業 + 網誌寫好幾天才完成…
▲參考來源:彼得(分頁小圓點縮放)學姊作品

分頁步驟

▲將所需圖放至 Assets
▲加入佔滿螢幕的 Scroll View
➞ Scroll View + cmd +View,設定上下左右對齊 (皆為 0)
➞大機型不想被瀏海擋住可設 Scroll View & Safe Area 上下左右對齊
➞出現紅色錯誤因 Scroll View 不知捲動範圍

▲加入 Image View:想滿版設為 Aspect Fill
▲ Image View 加入 Stack View
➞ Axis 選水平 Horizontal (依滑動方向而定),Alignment 為 Fill
➞ Distribution 選 Fill Equally, Spacing 為 0

▲ Stack View 上下左右間距設為 0
➞ Stack View + cmd + Content Layout Guide 設定上下左右對齊 (皆為 0)
➞ Scroll View 被 Stack View 填滿,由 Stack View 大小決定捲動範圍大小
➞ Scroll View 大小由裡面 Image View 決定
➞ 每個 Image View 大小由當初圖片大小決定

▲圖片寬高 = 螢幕寬高
➞ Image View + cmd + Frame Layout Guide: Equal Widths / Heights
➞ Frame Layout Guide 為 Scroll View 本身 frame
➞ 圖與 F 設一樣大時,圖和螢幕也會同大,因 Scroll View 和螢幕一樣大
Frame Layout Guide & Content Layout Guide 差異
➞ Content Layout Guide 含整個捲動內容 (大)
➞ Frame Layout Guide 為其中一部分,此指螢幕大小

▲加入其他 Image View:左側複製貼上再改圖內容
➞寬度為本來 3 倍 (藍框,Content Layout Guide)
➞ Scroll View 勾選 Paging Enabled 使其顯示完整圖

▲加入 Page Control
➞切記不能加在 Scroll View 裡,否則滑動時會隨之移動
➞選擇頁數,預設為 3 頁符合此案便不需調整
➞設定 Page Control 的 Auto Layout:水平置中
➞設定 Scroll View 的 delegate 為 View Controller
✅ 指定 data source / delegate 是型別 A 生成的東⻄

✅ 定義型別 A 遵從 protocol:UIScrollViewDelegate,直接寫 extension

extension ViewController: UIScrollViewDelegate {
}

✅ 在型別 A 裡定義 protocol 的 function

▲cmd 點 UIScrollViewDelegate 選 Jump to Definition 找功能
▲找到適合 function 後記下關鍵字 DidEndDecelerating
▲回 ViewController 打 didenddece 等會自動出現整個 function 可選
▲定義 function
➞ scrollView.contentOffset.x 為目前滑動的水平距離
◇ 因之前勾 Paging Enabled 一定停在某分頁,為分頁倍數(0, 568, 1136)
➞ scrollView.bounds.width 是 scroll view 寬度 = 分頁寬度(568)
➞ 2 者相除便可算出在位於第幾頁並更新小圓點顏色

▲ Page Control 自己也要拉 Action,點選不同小圓點使圖更動
➞依 currentPage 算出各頁起點座標(0,0) / (568,0) / (1136,0)
➞各座標為 Scroll View 要移動的量(offset)
➞ currentPage 原為 Int,而 CGPoint 要 CGFloat,所以要改

手勢縮放

▲ Inspector 設定 Scroll View — Zoom:Min 1,Max 5
▲剛 UIScrollViewDelegate 的 Jump to Definition 裡有 viewForZooming
▲回 ViewController 打 viewforz 等會自動出現整個 function 可選
▲其實裡面執行任務我還無法理解為何要這樣寫…之後懂了再補解釋

完整程式碼

--

--