えむじぃのアプリ開発

えむじぃのアプリ開発

元大手IT企業SE、現ベンチャー企業CTOのブログです。

【Swift】シェイクジェスチャー機能を実装する方法

今回はシェイクジェスチャー機能を実装する方法をこの記事で説明します。

この記事のポイント・becomeFirstResponder()を使用
・motionBegan()を使用
・motionEnded()を使用

シェイクジェスチャー機能を実装する方法

シェイクジェスチャー機能を実装するには以下のように設定します。

viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
        
    // shake
    self.becomeFirstResponder()

ジェスチャー開始時

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        // shake開始時の処理
    }
}

ジェスチャー終了時

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        // shake終了時の処理
    }
}

これでシェイクジェスチャー機能を使うことができます。