swif_播图
2016-11-24 本文已影响0人
ysweiwei
轮播图
实现图片自动翻转(UIViewController,UIScrollViewDelegate,Timer)
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
var scrollerView: UIScrollView! = nil
var pageC :UIPageControl! = nil
var timer : Timer! = nil
override func viewDidLoad() {
super.viewDidLoad()
let scro = UIScrollView (frame: CGRect(x: 0, y: 100, width: self.view.frame.width, height: self.view.frame.height))
scro.contentSize = CGSize(width: self.view.frame.width*6, height: 300)
scro.isPagingEnabled = true
scro.bounces = false
self.scrollerView = scro
self.view.addSubview(scro)
for index in 1...6{
let name = "\(index).jpg"
let image = UIImage(named: name)
let x = CGFloat(index - 1) * self.view.frame.size.width
let imageV = UIImageView(frame: CGRect(x: x, y: 0, width: self.view.frame.size.width, height: 300.0))
imageV.image = image
scro.addSubview(imageV)
scro.delegate = self
//
let page = UIPageControl(frame: CGRect(x: 100, y:350, width: self.view.frame.size.width-200, height: 30))
self.pageC = page
page.numberOfPages = 6
page.currentPage = 0
// page.addTarget(self, action: #selector(pageAction(page:)), for:.valueChanged)
page.addTarget(self, action: #selector(pageAction(page:)), for: .valueChanged)
self.view.addSubview(page)
//
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
self.timer.fire()
}
}
func timerAction(){
let offser = self.scrollerView.contentOffset
let width = self.view.frame.size.width
scrollerView.setContentOffset(CGPoint(x: offser.x+width, y:offser.y), animated: true)
if scrollerView.contentOffset.x >= width*4 {
let point = CGPoint(x:0,y:0)
self.scrollerView.contentOffset = point
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.timer = nil
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
let time = DispatchTime.now() + 1.0
DispatchQueue.main.asyncAfter(deadline: time){
if let _ = self.timer {
self.timer.fire()
}
}
}
func pageAction(page:UIPageControl) {
let index = page.currentPage //当前第几个
let point = CGPoint(x: CGFloat(index) * self.view.frame.size .width, y: 0)
//修改偏移量
self.scrollerView.setContentOffset(point, animated: true)
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let x = scrollerView.contentOffset.x
let width = self.view.frame.size.width
if(x >= width * 4){
self.pageC .currentPage = 0
}else{
self.pageC.currentPage = Int(x/width)
}
self.pageC.currentPage = Int(x/width)
}
}
}