基于分屏导航是平铺导航模式的主要实现方式,涉及的主要控件有分屏控件(UIPageControl)和屏幕滚动视图(UIScrollView).其中分屏控件是iOS标准控件.
ViewController.swift:
import UIKit
//定义屏幕宽度
let S_WIDTH: CGFloat = UIScreen.main.bounds.size.width
//定义屏幕高度
let S_HEIGHT: CGFloat = UIScreen.main.bounds.size.height
class ViewController: UIViewController ,UIScrollViewDelegate {
var scrollView: UIScrollView!
var pageControl: UIPageControl!
var imageView1: UIImageView!
var imageView2: UIImageView!
var imageView3: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//UIScrollView屏幕滚动视图
self.scrollView = UIScrollView()
self.view.addSubview(self.scrollView)
self.scrollView.delegate = self
self.scrollView.isPagingEnabled = true //设置屏幕滚动视图每次滑动时翻一屏
self.scrollView.showsHorizontalScrollIndicator = false //设置水平滚动条不显示
self.scrollView.showsVerticalScrollIndicator = false //设置垂直滚动条不显示
self.scrollView.contentSize = CGSize(width: S_WIDTH * 3, height: S_HEIGHT) //设置屏幕滚动视图的contentSize属性,表示屏幕滚动视图中内容视图(Content View)的大小
self.scrollView.frame = self.view.frame //设置屏幕滚动视图的frame属性为当前屏幕大小
//添加图片视图
self.imageView1 = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: S_WIDTH, height: S_HEIGHT))
self.imageView1.image = UIImage(named: "达芬奇-蒙娜丽莎.png")
self.imageView2 = UIImageView(frame: CGRect(x: S_WIDTH, y: 0.0, width: S_WIDTH, height: S_HEIGHT))
self.imageView2.image = UIImage(named: "罗丹-思想者.png")
self.imageView3 = UIImageView(frame: CGRect(x: 2 * S_WIDTH, y: 0.0, width: S_WIDTH, height: S_HEIGHT))
self.imageView3.image = UIImage(named: "保罗克利-肖像.png")
self.scrollView.addSubview(self.imageView1)
self.scrollView.addSubview(self.imageView2)
self.scrollView.addSubview(self.imageView3)
let pageControlWidth: CGFloat = 300.0
let pageControlHeight: CGFloat = 37.0
//创建分屏控件对象
self.pageControl = UIPageControl(frame: CGRect(x: (S_WIDTH - pageControlWidth)/2, y: S_HEIGHT - pageControlHeight, width: pageControlWidth, height: pageControlHeight))
//设置总屏数
self.pageControl.numberOfPages = 3
self.pageControl.addTarget(self, action: #selector(changePage(_:)), for: .valueChanged)
self.view.addSubview(self.pageControl)
}
// MARK: --实现UIScrollViewDelegate委托协议(屏幕滚动视图的事件处理)
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset
self.pageControl.currentPage = Int(offset.x / S_WIDTH)
}
// MARK: --实现UIPageControl事件处理
//根据分屏控件的当前屏幕属性(currentPage)重新调整了屏幕滚动视图的偏移量.为了使屏幕变化产生动画效果,使用了UIView的静态方法animateWithDuration来重新调整控件的偏移量
@objc func changePage(_ sender: AnyObject) {
UIView.animate(withDuration: 0.3, animations : {
let whichPage = self.pageControl.currentPage
self.scrollView.contentOffset = CGPoint(x: S_WIDTH * CGFloat(whichPage), y: 0)
})
}
}
image.png
网友评论