LoginSignup
55
53

More than 5 years have passed since last update.

[Swift]たった40行のUIScrollViewを使ったシンプルなチュートリアル画面サンプル

Last updated at Posted at 2015-01-29

tuto.gif

アプリの初回起動時などで横にスワイプさせるウォークスルー型のチュートリアル画面の作り方についてです。
UIPageViewControllerでも出来ますが、UIScrollViewの方がシンプルに作れたのでかんたんなものであれば十分かと思います。
ライブラリも色々ありますが、作ってしまったほうが楽な場合もあると思います。

下記コードで全部です。40行ほどで出来ました。

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    var scrollView: UIScrollView!
    var pageControll: UIPageControl!
    let pageNum = 4
    let pageColors:[Int:UIColor] = [1:UIColor.redColor(),2:UIColor.yellowColor(),3:UIColor.blueColor(),4:UIColor.greenColor()]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.scrollView = UIScrollView(frame: self.view.bounds)
        self.scrollView.contentSize = CGSizeMake(self.view.bounds.width * CGFloat(pageNum), self.view.bounds.height)
        self.scrollView.pagingEnabled = true
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.delegate = self;
        self.view.addSubview(self.scrollView)

        self.pageControll = UIPageControl(frame: CGRectMake(0, self.view.bounds.height-50, self.view.bounds.width, 50))
        self.pageControll.numberOfPages = pageNum
        self.pageControll.currentPage = 0
        self.view.addSubview(self.pageControll)

        for p in 1...pageNum {
            var v = UIView(frame: CGRectMake(self.view.bounds.width * CGFloat(p-1), 0, self.view.bounds.width, self.view.bounds.height))
            v.backgroundColor = self.pageColors[p]
            self.scrollView.addSubview(v)
        }
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        var pageProgress = Double(scrollView.contentOffset.x / scrollView.bounds.width)
        self.pageControll.currentPage = Int(round(pageProgress))

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
55
53
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
53