请事先在storyboard中添加UIScrollView和UIPageControl控件
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var scrollView: UIScrollView!
var images = [UIImageView]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 0...2{
let name = "image\(i + 1)"
let image = UIImageView(image: UIImage(named: name))
image.frame = CGRectMake(self.view.frame.width * CGFloat(i), 0, self.view.frame.width, scrollView.frame.height)
print(scrollView.frame)
print(self.view.frame)
image.contentMode = .ScaleAspectFit
scrollView.addSubview(image)
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self
images.append(image)
pageControl.numberOfPages = images.count
}
scrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(images.count), height: scrollView.frame.height)
pageControl.currentPage = 0
startTimer()
}
@IBAction func turnPage(sender: UIPageControl) {
stopTimer()
toPage(pageControl.currentPage)
resumeTimer()
}
func toPage(page:Int){
let dx = CGFloat(page) * self.view.frame.width
UIView.animateWithDuration(0.5, animations: {self.scrollView.contentOffset = CGPoint(x: dx, y: 0)})
}
var timer:NSTimer?
var running = false
func startTimer(){
if timer == nil{
timer = NSTimer(timeInterval: 3, target: self, selector: #selector(updateTime(_:)), userInfo: nil, repeats: true)
}
if !running{
running = true
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
}
}
func closeTimer(){
if running{
running = false
timer?.invalidate()
timer = nil
}
}
func stopTimer(){
if running{
timer?.fireDate = NSDate.distantFuture()
}
}
func resumeTimer(){
if running{
timer?.fireDate = NSDate(timeIntervalSinceNow: timer!.timeInterval)
}
}
func updateTime(timer:NSTimer){
let page = (pageControl.currentPage + 1) % images.count
toPage(page)
pageControl.currentPage = page
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController:UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView){
// print("scroll view did scroll")
let width = self.view.frame.width
let page = Int((scrollView.contentOffset.x + width / 2) / width)
self.pageControl.currentPage = page
}
func scrollViewWillBeginDragging(scrollView: UIScrollView){
print("scroll view will begin dragging")
stopTimer()
}
// func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>){
// print("scroll view will end dragging")
// }
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool){
print("scroll view did end dragging")
resumeTimer()
}
}
网友评论