import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
var scrollView:UIScrollView?
var picArr:[String]?
var pageControl:UIPageControl?
override func viewDidLoad() {
super.viewDidLoad()
picArr = ["java.png","scala.png","swift.png"]
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(scrollView!)
scrollView?.delegate = self
//设置内容大小
scrollView?.contentSize = CGSize(width: self.view.bounds.width*3, height: self.view.bounds.height)
//设置不显示滚动条
scrollView?.showsVerticalScrollIndicator = false
scrollView?.showsHorizontalScrollIndicator = false
//滚动时只能停留到某一页
scrollView?.isPagingEnabled = true
//for循环,枚举
for (seg,str) in (self.picArr?.enumerated())! {
let img = UIImageView(image: UIImage(named: str))
img.frame = CGRect(x: CGFloat(seg)*self.view.bounds.width, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
scrollView?.addSubview(img)
}
pageControl = UIPageControl(frame: CGRect(x: 80, y: self.view.bounds.height-50, width: 80, height: 30))
pageControl?.currentPage = 0
pageControl?.numberOfPages = (self.picArr?.count)!
pageControl?.addTarget(self, action: #selector(pageControlClick(_ :)), for: .valueChanged)
self.view.addSubview(pageControl!)
// Do any additional setup after loading the view, typically from a nib.
}
func pageControlClick(_ page:UIPageControl)
{
//根据点击的页数,计算scrollView需要显示的偏移量
var frame = scrollView?.frame
frame?.origin.x = (frame?.size.width)! * CGFloat(page.currentPage)
frame?.origin.y = 0
//展现当前页面内容
scrollView?.scrollRectToVisible(frame!, animated:true)
}
//减速停止的时候开始执行
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//通过scrollView内容的偏移计算当前显示的是第几页
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
//设置pageController的当前页
self.pageControl?.currentPage = page
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论