現(xiàn)在很多時候的App都要實(shí)現(xiàn)一些啟動廣告或更新說明頁面之類的需求, 這篇文章描述了一種簡單快捷, 物廉價美的解決方案. (與iPhone桌面翻頁效果一致)
筆者在試了N多種UIScrollView
的delegate方法后, 發(fā)現(xiàn)效果都不佳. 有些要么是滑動速度(velocity
)不對勁, 要么contentOffSet
的值不是預(yù)期. 令人抓狂. 直到我發(fā)現(xiàn)了UIScrollView
有這么個屬性: isPagingEnabled
. 哈哈問題便迎刃而解聊~
記載于此, 希望幫助到有需要的朋友們.
少廢話, 上代碼.
import UIKit
// global constants
let screenW = UIScreen.main.bounds.width
let screenH = UIScreen.main.bounds.height
let screenS = CGSize(width: screenW, height: screenH)
class AdvertisePageViewController: UIViewController, UIScrollViewDelegate {
var pageCtrl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
scrollView.contentSize = CGSize(width: screenW * 3, height: screenH)
scrollView.bounces = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self
//The key move!
//關(guān)鍵一步. 使得scrollView擁有翻頁效果,
//每一頁的frame就是初始化scrollView時的frame.
//設(shè)置為true后, UIKit會自動幫你處理加減速與偏移量等問題.
scrollView.isPagingEnabled = true
self.view.addSubview(scrollView)
let image1 = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: screenS))
let image2 = UIImageView(frame: CGRect(origin: CGPoint(x: screenW, y: 0), size: screenS))
let image3 = UIImageView(frame: CGRect(origin: CGPoint(x: screenW * 2, y: 0), size: screenS))
image1.image = UIImage(named: "ad_01")
image2.image = UIImage(named: "ad_02")
image3.image = UIImage(named: "ad_03")
scrollView.addSubview(image1)
scrollView.addSubview(image2)
scrollView.addSubview(image3)
//分頁指示器小紅點(diǎn)
pageCtrl = UIPageControl(frame: CGRect(x: 0, y: screenH-30, width: screenW, height: 30))
pageCtrl.numberOfPages = 3
pageCtrl.currentPageIndicatorTintColor = UIColor.orange
pageCtrl.pageIndicatorTintColor = UIColor.lightGray
pageCtrl.currentPage = 0
self.view.addSubview(pageCtrl)
self.view.bringSubview(toFront: pageCtrl)
}
以下是代理方法, 實(shí)現(xiàn)小紅點(diǎn)的變化問題. 實(shí)際上iOS桌面的滑動效果是在滑動停止時, 才變化的. 如下:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let xOffset = scrollView.contentOffset.x
if xOffset < 0.5 * screenW {
pageCtrl.currentPage = 0
} else if xOffset > 0.5 * screenW && xOffset < 1.5 * screenW {
pageCtrl.currentPage = 1
} else {
pageCtrl.currentPage = 2
}
}
這個Demo放到了我GitHub, 大家也可去下載看看效果~
大功告成! 希望能幫到大家~