Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách làm rung iPhone bằng Swift

Để 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

  1. Khởi tạo generator sớm (ví dụ trong viewDidLoad) và gọi prepare() để giảm độ trễ.
  2. Gọi impactOccurred() / notificationOccurred() tại thời điểm cần feedback.
  3. 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.