Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีทำให้ iPhone สั่น (Vibrate) ด้วย Swift

ใช้ AudioToolbox สำหรับการสั่นแบบดั้งเดิม และ UIFeedbackGenerator (iOS 10+) สำหรับ Haptic Feedback ที่หลากหลาย

วิธีที่ 1: System Vibration (Classic)

import AudioToolbox

// สั่นแบบเดิม (ยาว)
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

วิธีที่ 2: UIFeedbackGenerator (iOS 10+) - แนะนำ

ให้ Feedback แบบละเอียดกว่า เหมาะสำหรับ UX

Impact Feedback (การชน/แตะ)

// Heavy - แรง
let heavy = UIImpactFeedbackGenerator(style: .heavy)
heavy.impactOccurred()

// Medium - ปานกลาง
let medium = UIImpactFeedbackGenerator(style: .medium)
medium.impactOccurred()

// Light - เบา
let light = UIImpactFeedbackGenerator(style: .light)
light.impactOccurred()

// Soft - นุ่ม (iOS 13+)
let soft = UIImpactFeedbackGenerator(style: .soft)
soft.impactOccurred()

// Rigid - แข็ง (iOS 13+)
let rigid = UIImpactFeedbackGenerator(style: .rigid)
rigid.impactOccurred()

Selection Feedback (การเลือก)

let selection = UISelectionFeedbackGenerator()
selection.selectionChanged()

Notification Feedback (สำเร็จ/ผิดพลาด/เตือน)

let success = UINotificationFeedbackGenerator()
success.notificationOccurred(.success)

let warning = UINotificationFeedbackGenerator()
warning.notificationOccurred(.warning)

let error = UINotificationFeedbackGenerator()
error.notificationOccurred(.error)

Best Practice

  • Prepare Early: เรียก prepare() ก่อนใช้งาน เพื่อลด Latency
  • Reuse Generator: สร้าง Instance ไว้ใช้ซ้ำ ไม่ต้องสร้างใหม่ทุกครั้ง
  • Context เหมาะสม: ใช้ Style ที่ตรงกับ Action (Tap=Light, Success=Success, Error=Error)
class FeedbackManager {
    static let shared = FeedbackManager()
    private let impactLight = UIImpactFeedbackGenerator(style: .light)
    private let impactMedium = UIImpactFeedbackGenerator(style: .medium)
    private let notification = UINotificationFeedbackGenerator()
    
    private init() {
        impactLight.prepare()
        impactMedium.prepare()
        notification.prepare()
    }
    
    func light() { impactLight.impactOccurred() }
    func medium() { impactMedium.impactOccurred() }
    func success() { notification.notificationOccurred(.success) }
    func error() { notification.notificationOccurred(.error) }
}

// ใช้งานง่าย
FeedbackManager.shared.success()

หมายเหตุ

  • ไม่ทำงานบน Simulator ต้องทดสอบบน Device จริง
  • ต้องการ Device ที่รองรับ Taptic Engine (iPhone 7+)
  • ไม่สั่นได้ถ้าผู้ใช้ปิด System Haptics ใน Settings