首页 > 解决方案 > 如何像应用商店安装按钮一样让小振动?

问题描述

当我们按下应用商店中的安装按钮时,我正在尝试发出一点振动警报。我正在使用下面的代码,但这会产生长时间的振动,我需要与应用商店完全相同。许多应用程序以多种方式使用此功能,例如在收藏视图单元格中长按时会产生这种振动。

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

标签: iosobjective-cvibration

解决方案


我使用以下代码在我的应用程序中实现了相同的要求。我相信它会为你工作。

iOS 10 及更高版本您可以使用新的公共 API 来处理触觉反馈:UIFeedbackGenerator

let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
generator.notificationOccurred(.success)
generator.notificationOccurred(.warning)

// Light
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()

// Medium
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()

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

// Update: Call this method for vibration
// Update: it is mandetory method for vibration

generator.prepare()

对于 iOS 9 及更早版本,您可以使用 AudioToolBox。

import AudioToolbox

private let isDevice = TARGET_OS_SIMULATOR == 0

func vibrate() {
    if isDevice {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
    }
}

推荐阅读