iOS アプリで、初回起動時にチュートリアルを表示したいときにオススメのライブラリ「Gecco」のご紹介です。
こちらのライブラリでは、実際の画面にオーバーレイ表示して、各ボタンなどの使い方を説明する「コーチマーク」のチュートリアルを実装できます。
GitHub のページはこちらから。
GitHub – yukiasai/Gecco: Simply highlight items for your tutorial walkthrough, written in Swift
https://github.com/yukiasai/Gecco
実装方法は、まず Podfile に下記を追加して、pod install を実行します。
pod 'Gecco'
そして AnnotationViewController.swift というファイルを、下記の内容で追加します。
import UIKit
import Gecco
class AnnotationViewController: SpotlightViewController {
var annotationViews: [UIView] = []
var stepIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
// ボタン等を強調した時に表示したいテキストがある場合は、ここで annotationViews に追加する
let message1: UILabel = UILabel(frame: CGRect(x:0, y: 0, width: self.view.bounds.width, height: 150))
message.text = "チュートリアルで表示したいメッセージ1"
message.layer.position = CGPoint(x: self.view.bounds.width/2, y: 300)
self.view.addSubview(message)
annotationViews.append(message)
}
func next(_ labelAnimated: Bool) {
updateAnnotationView(labelAnimated)
let screenSize = UIScreen.main.bounds.size
switch stepIndex {
case 0:
spotlightView.appear(Spotlight.RoundedRect(center: CGPoint(x: screenSize.width/2, y: 320), size: CGSize(width: screenSize.width, height: 500), cornerRadius: 50))
case 1:
spotlightView.move(Spotlight.Oval(center: CGPoint(x: screenSize.width - 28, y: 42), diameter: 50))
case 2:
spotlightView.move(Spotlight.Oval(center: CGPoint(x: 28, y: 42), diameter: 50))
case 3:
dismiss(animated: true, completion: nil)
default:
break
}
stepIndex += 1
}
func updateAnnotationView(_ animated: Bool) {
annotationViews.enumerated().forEach { index, view in
UIView.animate(withDuration: animated ? 0.25 : 0) {
view.alpha = index == self.stepIndex ? 1 : 0
}
}
}
}
extension AnnotationViewController: SpotlightViewControllerDelegate {
func spotlightViewControllerWillPresent(_ viewController: SpotlightViewController, animated: Bool) {
next(false)
}
func spotlightViewControllerTapped(_ viewController: SpotlightViewController, isInsideSpotlight: Bool) {
next(true)
}
func spotlightViewControllerWillDismiss(_ viewController: SpotlightViewController, animated: Bool) {
spotlightView.disappear()
}
}
上記ファイルを追加したら、チュートリアルを表示したい ViewController の任意の場所で下記を実行します。
let viewController = AnnotationViewController() viewController.alpha = 0.5 present(viewController, animated: true, completion: nil)
基本的な処理は以上です。
なお、Storyboard は変更する必要はありません。
また、もしボタン等を強調する際にテキストを表示しない場合は、AnnotationViewController.swift の 6行目、15~19行目、23行目、42~48行目の処理は不要なので、コメントアウトするか削除してください。
またボタンを強調する際には、円形もしくは四角形を使い分けることができます。
// 円形の強調を使用する場合 Spotlight.Oval(center: [円の中心座標], diameter: [直径の値])) // 四角形の強調を使用する場合 Spotlight.RoundedRect(center: [中心座標], size: [四角形のサイズ], cornerRadius: [角丸のサイズ])
具体的な使用例は、AnnotationViewController.swift の 28行目、30行目、32行目をご参考にしていただければと思います。
以上、iOS アプリでチュートリアルを簡単に実装するためのライブラリ「Gecco」のご紹介でした。
サンプルコードは Storyboard を使用していたので、若干手こずりましたが、コツさえつかんでしまえばシンプルでとても使いやすかったです。
ご参考になれば幸いです。