使用UIScrollView&UIPageControl实现翻页效果的最佳方案

现在很多时候的App都要实现一些启动广告或更新说明页面之类的需求, 这篇文章描述了一种简单快捷, 物廉价美的解决方案. (与iPhone桌面翻页效果一致)

笔者在试了N多种UIScrollView的delegate方法后, 发现效果都不佳. 有些要么是滑动速度(velocity)不对劲, 要么contentOffSet的值不是预期. 令人抓狂. 直到我发现了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!
    //关键一步. 使得scrollView拥有翻页效果, 
    //每一页的frame就是初始化scrollView时的frame.
    //设置为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)
   
    //分页指示器小红点
    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)
  }

以下是代理方法, 实现小红点的变化问题. 实际上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, 大家也可去下载看看效果~

大功告成! 希望能帮到大家~

你可能感兴趣的:(使用UIScrollView&UIPageControl实现翻页效果的最佳方案)