如何使iPhone使用Swift震动?

我需要使iPhone震动,但我不知道如何在Swift中做到这一点。 我知道在Objective-C中,你只需写:

import AudioToolbox AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); 

但是这不适合我。

简短的例子:

 import UIKit import AudioToolbox class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } 

加载到你的手机,它会振动。 你可以把它放在函数或IBAction中,如你所愿。

在iPhone 7或7 Plus的iOS 10中,请尝试:

 let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() 

我们可以在Xcode7.1中做到这一点

 import UIKit import AudioToolbox class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() AudioServicesPlayAlertSound(kSystemSoundID_Vibrate) } } 

其他振动types:

 import AudioToolbox AudioServicesPlaySystemSound(1519) // Actuate `Peek` feedback (weak boom) AudioServicesPlaySystemSound(1520) // Actuate `Pop` feedback (strong boom) AudioServicesPlaySystemSound(1521) // Actuate `Nope` feedback (series of three weak booms) 

更多关于振动 – http://www.mikitamanko.com/blog/2017/01/29/haptic-feedback-with-uifeedbackgenerator/

 AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) 

对于iOS 10.0+您可以尝试UIFeedbackGenerator

上面的简单的viewController,只是在你的testing“单一视图应用程序”

 import UIKit class ViewController: UIViewController { var i = 0 override func viewDidLoad() { super.viewDidLoad() let btn = UIButton() self.view.addSubview(btn) btn.translatesAutoresizingMaskIntoConstraints = false btn.widthAnchor.constraint(equalToConstant: 160).isActive = true btn.heightAnchor.constraint(equalToConstant: 160).isActive = true btn.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true btn.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true btn.setTitle("Tap me!", for: .normal) btn.setTitleColor(UIColor.red, for: .normal) btn.addTarget(self, action: #selector(tapped), for: .touchUpInside) } func tapped() { i += 1 print("Running \(i)") switch i { case 1: let generator = UINotificationFeedbackGenerator() generator.notificationOccurred(.error) case 2: let generator = UINotificationFeedbackGenerator() generator.notificationOccurred(.success) case 3: let generator = UINotificationFeedbackGenerator() generator.notificationOccurred(.warning) case 4: let generator = UIImpactFeedbackGenerator(style: .light) generator.impactOccurred() case 5: let generator = UIImpactFeedbackGenerator(style: .medium) generator.impactOccurred() case 6: let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() default: let generator = UISelectionFeedbackGenerator() generator.selectionChanged() i = 0 } } } 
Interesting Posts