为了使iPhone迅速振动,我们将使用两种不同的方法。首先创建一个新项目,并在主View控制器中添加四个不同的按钮。
现在,在您的视图控制器类中导入AudioToolbox框架。
对于第一个按钮,添加一个动作并编写以下代码,如下所示:
@IBAction func actionButtonOne(_ sender: Any) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) }
这会在您的设备上产生长时间的振动反馈。现在,要在装有iOS 10或更高版本的设备上创建更多的振动效果,我们将为所有四个不同的按钮添加方法。
@IBAction func actionButtonTwo(_ sender: Any) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() } @IBAction func actionButtonThree(_ sender: Any) { let generator = UIImpactFeedbackGenerator(style: .light) generator.impactOccurred() } @IBAction func actionButtonFour(_ sender: Any) { let generator = UIImpactFeedbackGenerator(style: .medium) generator.impactOccurred() }
在以上三种方法中,我们使用UIImpact反馈生成器来生成三种不同类型的反馈。现在,在设备上运行该应用程序,并在按下这些按钮时感觉到振动。可悲的是,由于振动反馈,在此示例中无法显示输出。