→ Swift Archive

[SwiftUI] 햅틱 반응 적용하기

Swift librarian 2023. 11. 15. 03:20

iOS 앱을 만들다보면 햅틱 반응이 앱을 한층 더 풍부하게 만들어 준다는 생각이 든다. 물론 무분별하게 쓰면 안되겠지만 그래도 강조하고 싶은 인터렉션이나 사용자 관점에서 좋은 경험을 줄 수 있다면 적극적으로 사용하는 것도 좋을 것 같다.

 

SensoryFeedback

우선 최근 17.0 버전부터 지원하는 SensoryFeedback 이라는 것이 있다. 

사용방법은 아래와 같다. 아래와 같이 버튼과 연결하여 hapticFeedbacktrue 가 되면 .success 라는 햅틱 피드백을 줄 수 있다.

import SwiftUI

struct HapticView: View {
    @State var hapticFeedback = false
    
    var body: some View {
        Button("햅틱") {
            hapticFeedback = true
        }
        .sensoryFeedback(.success, trigger: hapticFeedback)
    }
}

내가 구현한 HapticFeedback

아래는 내가 쓰는 햅틱 방법이다. 보통 햅틱을 action 과 함께 쓰기 때문에 action 과 같이 끼워 넣는다. 방법이 틀릴 수는 있겠지만 나는 정적(static) 메서드로 구현하여 객체의 인스턴스를 생성할 필요가 없고, 간단하게 햅틱 피드백을 호출할 수 있도록 만들었다.

import SwiftUI

final class Haptic {
    static func notification(type: UINotificationFeedbackGenerator.FeedbackType) {
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(type)
    }
    
    static func impact(style: UIImpactFeedbackGenerator.FeedbackStyle) {
        let generator = UIImpactFeedbackGenerator(style: style)
        generator.impactOccurred()
    }
}

사용방법

아래와 같이 아주아주 간단하게 사용할 수 있다. 어떠한 조건을 걸어줄 수도 있고, 활용도가 높고 사용하기 편해서 나는 이렇게 쓴다.

import SwiftUI

struct HapticView: View {    
    var body: some View {
        Button("햅틱") {
            Haptic.impact(style: .soft)
        }
    }
}

 

참고자료

 

SensoryFeedback | Apple Developer Documentation

Represents a type of haptic and/or audio feedback that can be played.

developer.apple.com