网上参考OBJC写的用ScrollView图片轮播效果,照着画了个,先上效果图:
附上代码:
1 @IBOutlet weak var pc: UIPageControl! 2 @IBOutlet weak var sv:UIScrollView! 3 4 var timer:NSTimer! 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 9 for i in 1...6{ //loading the images 10 let image = UIImage(named: "pic\(i).jpg")! 11 let x = CGFloat(i - 1) * self.view.frame.width //这一步获取ScrollView的宽度时我用IPHONE6实体机测试是320,右边会出现第二张图片的一部分,最后还是用ROOT VIEW的宽度 12 var imageView = UIImageView(frame: CGRectMake(x, 0, self.view.frame.width, sv.bounds.height)) 13 imageView.image = image 14 sv.pagingEnabled = true 15 sv.showsHorizontalScrollIndicator = false 16 sv.scrollEnabled = true 17 sv.addSubview(imageView) 18 sv.delegate = self 19 } 20 21 sv.contentSize = CGSizeMake((self.view.frame.width * 6), sv.frame.height) 22 pc.numberOfPages = 6 23 pc.currentPageIndicatorTintColor = UIColor.redColor() 24 pc.pageIndicatorTintColor = UIColor.whiteColor() 25 addTimer() 26 27 } 28 29 func scrollViewDidScroll(scrollView: UIScrollView) { 30 let width = self.view.frame.width 31 let offsetX = scrollView.contentOffset.x 32 let index = (offsetX + width / 2) / width 33 pc.currentPage = Int(index) 34 } 35 36 func scrollViewWillBeginDragging(scrollView: UIScrollView) { 37 removeTimer() 38 } 39 40 func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { 41 addTimer() 42 } 43 44 func addTimer() { 45 timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "nextImage", userInfo: nil, repeats: true) 46 } 47 48 func removeTimer() { 49 timer.invalidate() 50 } 51 52 53 func nextImage() { 54 var pageIndex = pc.currentPage 55 if pageIndex == 5 { 56 pageIndex = 0 57 } else { 58 pageIndex++ 59 } 60 61 var offsetX = CGFloat(pageIndex) * self.view.frame.width 62 sv.setContentOffset(CGPointMake(offsetX, 0), animated: true) 63 }