LoginSignup
5
4

More than 5 years have passed since last update.

UIFeedbackGeneratorを簡単に使えるようにする

Posted at

開発環境

  • Xcode10.2
  • Swift 5.0

UIFeedbackGeneratorとは

Apple公式から引用

概要
このクラスのインスタンスを自分でサブクラス化したり作成したりしないでください。代わりに、提供されている具象サブクラスの1つをインスタンス化してください。

UIImpactFeedbackGenerator。影響が発生したことを示すには、影響フィードバックジェネレータを使用します。たとえば、ユーザーインターフェイスオブジェクトが何かにぶつかったり、所定の位置に固定されたときに、インパクトフィードバックを引き起こすことがあります。

UISelectionFeedbackGenerator。選択の変化を示すために選択フィードバックジェネレータを使用します。

UINotificationFeedbackGenerator。成功、失敗、および警告を示すために通知フィードバックジェネレータを使用します。

何かのアクションのフィードバックとしてユーザさんの端末をブルッてさせてフィードバックするやつです。

通常の実装方法

UIFeedbackGeneratorの使い方と便利に使えるライブラリから引用させていただきました。

class ViewController: UIViewController {

    private let feedbackGenerator: Any? = {
        if #available(iOS 10.0, *) {
            let generator: UIImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
            generator.prepare()
            return generator
        } else {
            return nil
        }
    }()

    @IBAction private func light() {
        if #available(iOS 10.0, *), let generator = feedbackGenerator as? UIImpactFeedbackGenerator {
            generator.impactOccurred()
        }
    }

各VCに記述するにはしんどいなという印象でした。

簡単に使う方法

以下の構造体でラップして利用します。


/// UIFeedbackGeneratorを簡単に利用するためのラッパー
struct Feedbacker {

  static func notice(type: UINotificationFeedbackGenerator.FeedbackType) {
    if #available(iOS 10.0, *) {
      let generator = UINotificationFeedbackGenerator()
      generator.prepare()
      generator.notificationOccurred(type)
    }
  }

  static func impact(style: UIImpactFeedbackGenerator.FeedbackStyle) {
    if #available(iOS 10.0, *) {
      let generator = UIImpactFeedbackGenerator(style: style)
      generator.prepare()
      generator.impactOccurred()
    }
  }

  static func selection() {
    if #available(iOS 10.0, *) {
      let generator = UISelectionFeedbackGenerator()
      generator.prepare()
      generator.selectionChanged()
    }
  }

}

使い方

フィードバックをさせたいところでstaticメソッドをコールします。

/// 例
override func viewDidLoad() {
  // ViewControllerの読み込みが終わったらフィードバック
  Feedbacker.notice(type: .success)
}

コールの仕方は以下になりますので用途によって使い分けてください。

// notice
Feedbacker.notice(type: .success)
Feedbacker.notice(type: .warning)
Feedbacker.notice(type: .error)

// impact
Feedbacker.impact(style: .heavy)
Feedbacker.impact(style: .light)
Feedbacker.impact(style: .medium)

// selection
Feedbacker.selection()

おわり

間違えてる部分や編集リクエストありましたらよろしくお願いいたします

5
4
0

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
5
4