import UIKit
let imageCount = 5
//屏幕的宽
let kscreenWidth = UIScreen.main.bounds.size.width
//屏幕的高
let kscreenHeight = UIScreen.main.bounds.size.height
class ViewController: UIViewController,UIScrollViewDelegate {
//定义一个定时器属性
var time:Timer!
lazy var scrollView : UIScrollView = {
let scr = UIScrollView(frame: UIScreen.main.bounds)
scr.contentSize = CGSize(width: CGFloat (imageCount) * kscreenWidth, height: kscreenHeight)
scr.isPagingEnabled = true
for i in 0..<imageCount{
let imageView = UIImageView(frame: CGRect(x: CGFloat(i) * kscreenWidth, y: 0, width: kscreenWidth, height: kscreenHeight))
imageView.image = UIImage(named:"\(i).jpg")
scr.addSubview(imageView)
}
//设置scrollView的偏移量
scr.contentOffset.x = kscreenWidth
//给scr设置代理
scr.delegate = self
return scr
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//scrollView添加到父视图
self.view.addSubview(self.scrollView)
//添加定时器
self.time = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(timeAction), userInfo: nil, repeats: true)
}
//MARK:- 定时器的关联方法
func timeAction() {
let page = self.scrollView.contentOffset.x / kscreenWidth
if page == 3.0 {
self.scrollView.contentOffset.x = kscreenWidth
}else{
self.scrollView.contentOffset.x += kscreenWidth
}
}
//MARK:- 开始拖拽的代理方法
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//停止定时器的方法
self.time.invalidate()
//销毁定时器
self.time = nil
}
//MARK:- 结束拖拽的代理方法
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//重新开启定时器
self.time = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(timeAction), userInfo: nil, repeats: true)
}
//scrollView减速完成触发的方法
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / kscreenWidth
if page == CGFloat (imageCount) - 1 {
scrollView.contentOffset.x = kscreenWidth
}else if page == 0{
scrollView.contentOffset.x = CGFloat(imageCount) - 2 * kscreenWidth
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论