已更新至 Xcode7.2、Swift2.1
在第一次打開App或者App更新後通常用引導頁來展示産品特性
我們用
NSUserDefaults
類來判斷程式是不是第一次啟動或是否更新,在
AppDelegate.swift
中加入以下代碼:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 得到目前應用的版本号
let infoDictionary = NSBundle.mainBundle().infoDictionary
let currentAppVersion = infoDictionary!["CFBundleShortVersionString"] as! String
// 取出之前儲存的版本号
let userDefaults = NSUserDefaults.standardUserDefaults()
let appVersion = userDefaults.stringForKey("appVersion")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// 如果 appVersion 為 nil 說明是第一次啟動;如果 appVersion 不等于 currentAppVersion 說明是更新了
if appVersion == nil || appVersion != currentAppVersion {
// 儲存最新的版本号
userDefaults.setValue(currentAppVersion, forKey: "appVersion")
let guideViewController = storyboard.instantiateViewControllerWithIdentifier("GuideViewController") as! GuideViewController
self.window?.rootViewController = guideViewController
}
return true
}
在
GuideViewController
中,我們用
UIScrollView
來裝載我們的引導頁:
class GuideViewController: UIViewController {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var startButton: UIButton!
private var scrollView: UIScrollView!
private let numOfPages = 3
override func viewDidLoad() {
super.viewDidLoad()
let frame = self.view.bounds
scrollView = UIScrollView(frame: frame)
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
scrollView.contentOffset = CGPointZero
// 将 scrollView 的 contentSize 設為螢幕寬度的3倍(根據實際情況改變)
scrollView.contentSize = CGSize(width: frame.size.width * CGFloat(numOfPages), height: frame.size.height)
scrollView.delegate = self
for index in 0..<numOfPages {
// 這裡注意圖檔的命名
let imageView = UIImageView(image: UIImage(named: "GuideImage\(index + 1)"))
imageView.frame = CGRect(x: frame.size.width * CGFloat(index), y: 0, width: frame.size.width, height: frame.size.height)
scrollView.addSubview(imageView)
}
self.view.insertSubview(scrollView, atIndex: 0)
// 給開始按鈕設定圓角
startButton.layer.cornerRadius = 15.0
// 隐藏開始按鈕
startButton.alpha = 0.0
}
// 隐藏狀态欄
override func prefersStatusBarHidden() -> Bool {
return true
}
}
最後我們讓
GuideViewController
遵循
UIScrollViewDelegate
協定,在這裡判斷是否滑動到最後一張以顯示進入按鈕:
// MARK: - UIScrollViewDelegate
extension GuideViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset
// 随着滑動改變pageControl的狀态
pageControl.currentPage = Int(offset.x / view.bounds.width)
// 因為currentPage是從0開始,是以numOfPages減1
if pageControl.currentPage == numOfPages - 1 {
UIView.animateWithDuration(0.5) {
self.startButton.alpha = 1.0
}
} else {
UIView.animateWithDuration(0.2) {
self.startButton.alpha = 0.0
}
}
}
}
在上面的代碼中,為了顯得自然我們給進入按鈕加入了一點動畫 :]
最終效果如下:
GuideScreenshot.gif
Github位址:https://github.com/GuiminChu/JianshuExample
文/老初(簡書作者)
著作權歸作者所有,轉載請聯系作者獲得授權,并标注“簡書作者”。