pageControl和scrollVIE可以联合使用,scrollview主要有几个属性 一个contentSize 是总共的视图的容量大小,每个view的x坐标要不相同 随后实现scrollview的协议,当scrollview翻页的时候,来实现pagecontrol的翻页,读出他的contentoffset事偏移量 为一个CGPoint 读出后,x的坐标除以viewwidth便可以实现pagecontrol实现的不同了,随后在pagecontrol中添加目标时间,当值发生改变时,引起事件,随后导致scrollview翻页效果的产生即可,要记住scrollview的pageControl的属性一定要设置为true,否则无法实现翻页的效果 下面看具体的代码
import UIKit class ViewController: UIViewController,UIScrollViewDelegate { var scrollView:UIScrollView! var pageControl:UIPageControl! var viewHeight:CGFloat = 0 var viewWidth:CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //初始化 viewHeight = self.view.frame.size.height viewWidth = self.view.frame.size.width //创建屏幕滚动的视图 self.scrollView = UIScrollView(frame: CGRectMake(0,0,viewWidth,viewHeight)) //包含的大小 高度不变 宽度变为原来的3倍 self.scrollView.contentSize = CGSize(width: viewWidth * 3, height: viewHeight) //随着页面变化器而变化 scrollView.pagingEnabled = true //设置代理 scrollView.delegate = self //设置图片 还要设置每个imageView的位置关系 let image1 = UIImage(named: "1") var imageView1 = UIImageView(image: image1) imageView1.frame = CGRectMake(0, 0, viewWidth, viewHeight) let image2 = UIImage(named: "2") var imageView2 = UIImageView(image: image2) imageView2.frame = CGRectMake(viewWidth, 0, viewWidth, viewHeight) let image3 = UIImage(named: "3") var imageView3 = UIImageView(image: image3) imageView3.frame = CGRectMake(viewWidth * 2,viewHeight, viewWidth, viewHeight) //添加三个视图 scrollView.addSubview(imageView3) scrollView.addSubview(imageView2) scrollView.addSubview(imageView1) self.view.addSubview(scrollView) //初始化分屏控制器 var pageControlHeight:CGFloat = 38.0 var pageControlWidth:CGFloat = 120.0 //创建大小 var pageControlFrame = CGRectMake((viewWidth - pageControlWidth) / 2, (viewHeight - pageControlHeight), pageControlWidth, pageControlHeight) pageControl = UIPageControl(frame: pageControlFrame) //背景颜色 pageControl.backgroundColor = UIColor.blackColor() //透明度 pageControl.alpha = 0.5 pageControl.numberOfPages = 3 pageControl.currentPage = 0 pageControl.addTarget(self, action: "changePage:", forControlEvents: .ValueChanged) self.view.addSubview(pageControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //实现代理 func scrollViewDidScroll(scrollView: UIScrollView) { var offset = scrollView.contentOffset //目前的页数 pageControl.currentPage = Int(offset.x) / Int(viewWidth) } func changePage(sender:AnyObject) { //设置一个动画 UIView.animateWithDuration(0.3, animations: { var whichPage = self.pageControl.currentPage self.scrollView.contentOffset = CGPointMake(CGFloat(whichPage) * self.viewWidth, 0) }) } }