しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

【Swift】BWWalkthroughでおしゃれなウォークスルーを実装する

BWWalkthroughというライブラリを試してみました。

github.com

CocoaPodsでインストールします。

pod 'BWWalkthrough'

まずはStoryboardにViewControllerを作成し、BWWalkthroughViewControllerに紐付けます。

f:id:llcc:20160615235750p:plain

画面上に閉じるや次へボタンを設置したら、BWWalkthroughViewControllerに紐付けます。

f:id:llcc:20160615235938p:plain

ViewControllerでBWWalkthroughViewControllerに対してaddViewControllerしてからBWWalkthroughViewControllerをpresentします。

import UIKit
import BWWalkthrough

class ViewController: UIViewController {
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        let vc1 = UIViewController()
        vc1.title = "VC1"
        vc1.view.backgroundColor = UIColor.blueColor()
        let vc2 = UIViewController()
        vc2.title = "VC2"
        vc2.view.backgroundColor = UIColor.greenColor()
        
        let vc = BWWalkthroughViewController()
        vc.addViewController(vc1)
        vc.addViewController(vc2)
        presentViewController(vc, animated: true, completion: nil)
    }
}

これでウォークスルーを表示する事ができました。

f:id:llcc:20160616000230p:plain

BWWalkthroughViewControllerDelegateを使えば各ボタンを押下した時にメソッドが呼ばれます。

@objc public protocol BWWalkthroughViewControllerDelegate{
    
    @objc optional func walkthroughCloseButtonPressed()              // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed.
    @objc optional func walkthroughNextButtonPressed()               //
    @objc optional func walkthroughPrevButtonPressed()               //
    @objc optional func walkthroughPageDidChange(pageNumber:Int)     // Called when current page changes
}

BWWalkthroughViewControllerに渡すViewControllerがBWWalkthroughPageに準拠している場合、walkthroughDidScrollというメソッドが呼ばれます。
このメソッドはスクロールの時に呼ばれるので、スクロールに従ってアニメーションさせたい時などに活用できます。

import UIKit
import BWWalkthrough

class ViewController: UIViewController {
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        let vc1 = UIViewController()
        vc1.title = "VC1"
        vc1.view.backgroundColor = UIColor.blueColor()
        let vc2 = Vc2()
        vc2.title = "VC2"
        vc2.view.backgroundColor = UIColor.greenColor()
        
        let vc = UIStoryboard(name: "Sample", bundle: nil).instantiateInitialViewController()! as! BWWalkthroughViewController
        vc.addViewController(vc1)
        vc.addViewController(vc2)
        presentViewController(vc, animated: true, completion: nil)
    }
}

class Vc2: UIViewController, BWWalkthroughPage {
    func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {
        print("walkthroughDidScroll")
        print(position)
        print(offset)
    }
}

f:id:llcc:20160616000822p:plain