7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】触覚フィードバックボタンを実装する

Last updated at Posted at 2023-06-16

はじめに

iOS17からSwiftUIの標準機能で触覚フィードバックが追加されました!

しかし、iOS16以下でも触覚フィードバックは使用したいです。
今回はiOS16以下でも簡単に触覚フィードバックを使用できる方法を記事にします。

実装

Haptics
import class UIKit.UIImpactFeedbackGenerator
import class UIKit.UINotificationFeedbackGenerator
import class UIKit.UISelectionFeedbackGenerator

public func playImpactHaptic(_ style: UIImpactFeedbackGenerator.FeedbackStyle) {
    let generator = UIImpactFeedbackGenerator(style: style)
    generator.impactOccurred()
}

public func playNotificationHaptic(_ type: UINotificationFeedbackGenerator.FeedbackType) {
    let generator = UINotificationFeedbackGenerator()
    generator.notificationOccurred(type)
}

public func playSelectionHaptic() {
    let generator = UISelectionFeedbackGenerator()
    generator.selectionChanged()
}

public enum Haptics {
    case impact(_ style: UIImpactFeedbackGenerator.FeedbackStyle)
    case notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
    case selection
    
    public func play() {
        switch self {
        case let .impact(style):
            playImpactHaptic(style)
        case let .notification(type):
            playNotificationHaptic(type)
        case .selection:
            playSelectionHaptic()
        }
    }
}
import SwiftUI

public struct Button<T: View>: View {
    private let haptics: Haptics

    private let action: () -> Void
    
    private let label: () -> T
    
    public init(haptics: Haptics, action: @escaping () -> Void, label: @escaping () -> T) {
        self.haptics = haptics
        self.action = action
        self.label = label
    }

    public var body: some View {
        SwiftUI.Button {
            haptics.play()
            action()
        } label: {
            label()
        }
    }
}

使い方

ボタンとして使う

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(haptics: .notification(.success)) {
            // action
        } label: {
            Text("ボタン")
        }
    }
}

関数で使う

import SwiftUI

struct ContentView: View {
    var body: some View {
        SwiftUI.Button {
            playImpactHaptic(.medium)
        } label: {
            Text("ボタン")
        }
    }
}

おわり

今回使用したコードでライブラリを作成しました!

7
2
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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?