1. 程式人生 > >- StoryBoard間切換與UIScrollView控制元件實現圖片輪播

- StoryBoard間切換與UIScrollView控制元件實現圖片輪播

介面切換

在專案中可以把耦合度比較高的介面放在通過一個StoryBoard中,可以按照功能使用多個StoryBoard搭建介面,這樣便於專案維護以及多人開發,對於多個StoryBoard間切換,可以使用以下程式碼:

@IBAction func ChangeOne(sender: UIButton) {
        var oneStoryBoard:UIStoryboard = UIStoryboard(name: "One", bundle: NSBundle.mainBundle())
        let oneController:UIViewController = oneStoryBoard.instantiateViewControllerWithIdentifier("oneId") as UIViewController
        self.navigationController?.pushViewController(oneController, animated: true)
    }
需要說明的是上面的"One"是One.storyboard,"oneId"是下圖中的Storyboard ID

還有一個需要注意的就是切換介面的主介面必須是Navigation Contoller


UIScrollView實現圖片輪播

// // Two.swift // MultStoryBoardChanged // // Created by System Administrator on 15/2/6. // Copyright (c) 2015年 jwzhangjie. All rights reserved. // import UIKit class Two: UIViewController, UIScrollViewDelegate{ @IBOutlet weak var scrollview: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! var timer:NSTimer! override func viewDidLoad() { super.viewDidLoad(); //image width let imageW:CGFloat = self.scrollview.frame.size.width; let imageH:CGFloat = self.scrollview.frame.size.height; var imageY:CGFloat = 0; var totalCount:NSInteger = 5; for index in 0..<totalCount{ var imageView:UIImageView = UIImageView(); let imageX:CGFloat = CGFloat(index) * imageW; imageView.frame = CGRectMake(imageX, imageY, imageW, imageH); let name:NSString = NSString(format: "image_0%d", index+1); imageView.image = UIImage(named: name); self.scrollview.showsHorizontalScrollIndicator = false; self.scrollview.addSubview(imageView); } let contentW:CGFloat = imageW * CGFloat(totalCount); self.scrollview.contentSize = CGSizeMake(contentW, 0); self.scrollview.pagingEnabled = true; self.scrollview.delegate = self;

self.pageControl.numberOfPages = totalCount; self.addTimer() } func nextImage(sender:AnyObject!){ var page:Int = self.pageControl.currentPage; if(page == 4){ page = 0; }else{ ++page; } let x:CGFloat = CGFloat(page) * self.scrollview.frame.size.width; self.scrollview.contentOffset = CGPointMake(x, 0); } func scrollViewDidScroll(scrollView: UIScrollView) { let scrollviewW:CGFloat = scrollview.frame.size.width; let x:CGFloat = scrollview.contentOffset.x; let page:Int = (Int)((x + scrollviewW / 2) / scrollviewW); self.pageControl.currentPage = page; } func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.removeTimer(); } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.addTimer(); } func addTimer(){ self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "nextImage:", userInfo: nil, repeats: true); NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes); } func removeTimer(){ self.timer.invalidate(); } }


需要注意的是XCode6.1裡面

for index in 0..<totalCount{
0..<是半區間,包頭不包尾    ...全區間