Để tạo phản hồi rung (haptic feedback) trên iPhone bằng Swift, chúng ta có 2 cách chính: dùng AudioToolbox (cũ, rung đơn giản) và UIFeedbackGenerator (iOS 10+, đa dạng, tinh tế).
Cách 1: AudioToolbox (Rung cơ bản, iOS cũ)
import AudioToolbox
@IBAction func vibrateBasic(_ sender: Any) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
Tạo rung dài, đơn giản. Hoạt động trên mọi iPhone có motor rung.
Cách 2: UIFeedbackGenerator (iOS 10+, khuyến khích)
Cung cấp 3 loại rung impact (va chạm) với cường độ khác nhau:
@IBAction func vibrateHeavy(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
}
@IBAction func vibrateLight(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
}
@IBAction func vibrateMedium(_ sender: Any) {
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
}
Các loại Feedback Generator khác
- UINotificationFeedbackGenerator: .success, .warning, .error (dùng cho thông báo kết quả).
- UISelectionFeedbackGenerator: Dùng khi user chọn item (picker, segment control).
// Ví dụ Notification feedback
let notification = UINotificationFeedbackGenerator()
notification.notificationOccurred(.success) // Rung kiểu "thành công"
Best Practice
- Khởi tạo generator sớm (ví dụ trong
viewDidLoad) và gọiprepare()để giảm độ trễ. - Gọi
impactOccurred()/notificationOccurred()tại thời điểm cần feedback. - Không lạm dụng – chỉ dùng khi có tương tác ý nghĩa (tap button, toggle, error, success).
Lưu ý: Rung không hoạt động trên Simulator. Cần test trên thiết bị thật.