標籤:
網上參考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 images10 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 = image14 sv.pagingEnabled = true15 sv.showsHorizontalScrollIndicator = false16 sv.scrollEnabled = true17 sv.addSubview(imageView)18 sv.delegate = self19 }20 21 sv.contentSize = CGSizeMake((self.view.frame.width * 6), sv.frame.height)22 pc.numberOfPages = 623 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.width31 let offsetX = scrollView.contentOffset.x32 let index = (offsetX + width / 2) / width33 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.currentPage55 if pageIndex == 5 {56 pageIndex = 057 } else {58 pageIndex++59 }60 61 var offsetX = CGFloat(pageIndex) * self.view.frame.width62 sv.setContentOffset(CGPointMake(offsetX, 0), animated: true)63 }
SWIFT用ScrollView加圖片製作Banner