1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
@IBOutlet weak var pageControl1: UIPageControl! @IBOutlet weak var scrollView1: UIScrollView! let images = ["s1", "s2", "s3"] var timer = NSTimer() var imageWidth:CGFloat! var imageHeight:CGFloat! override func viewDidLoad() { super.viewDidLoad() } 该方法计算了真实地scrollView地frame的大小 详见:http://benjaminwhx.com/2015/12/03/IOS%E9%94%99%E8%AF%AF%E6%80%BB%E7%BB%93/ */ override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let imageY: CGFloat = 0 imageWidth = self.scrollView1.frame.size.width imageHeight = self.scrollView1.frame.size.height for i in 0..<images.count { let imageX = imageWidth * CGFloat(i) let imageView = UIImageView(image: UIImage(named: images[i])) imageView.frame = CGRectMake(imageX, imageY, imageWidth, imageHeight) self.scrollView1.addSubview(imageView) } let contentWidth = CGFloat(images.count) * imageWidth self.scrollView1.contentSize = CGSizeMake(contentWidth, 0) self.scrollView1.pagingEnabled = true self.scrollView1.delegate = self scrollView1.showsHorizontalScrollIndicator = false scrollView1.showsVerticalScrollIndicator = false self.pageControl1.numberOfPages = images.count self.pageControl1.currentPage = 0 addTimer() } func nextImage() { var currentPage = self.pageControl1.currentPage if currentPage == images.count-1 { currentPage = 0 } else { currentPage++ } let offsetX = imageWidth * CGFloat(currentPage) self.scrollView1.contentOffset = CGPointMake(offsetX, 0) } func scrollViewDidScroll(scrollView: UIScrollView) { let offsetX = self.scrollView1.contentOffset.x self.pageControl1.currentPage = Int(offsetX / imageWidth) } @IBAction func pageValueChanged(sender: UIPageControl) { print("value changed, current page: \(sender.currentPage)") let offsetX = imageWidth * CGFloat(sender.currentPage) self.scrollView1.contentOffset = CGPointMake(offsetX, 0) } func addTimer() { self.timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "nextImage", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes) } func removeTimer() { self.timer.invalidate() } func scrollViewWillBeginDragging(scrollView: UIScrollView) { removeTimer() } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { addTimer() }
}
|