如何让我的 iPhone 在点击一个按钮时振动两次?

7

我希望在点击按钮时,可以让我的iPhone震动两次(就像收到短信的震动提醒一样)

使用AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))只能得到一个普通的震动,但我想要两个短震:/。


1
https://dev59.com/O2cs5IYBdhLWcg3wSiJo - shim
4个回答

33

iOS 10更新

iOS 10提供了几种新的方法来实现这个功能,而且代码很短。

方法1 - UIImpactFeedbackGenerator

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

方法2 - UINotificationFeedbackGenerator

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

方法三 - UISelectionFeedbackGenerator

let feedbackGenerator = UISelectionFeedbackGenerator()
feedbackGenerator.selectionChanged()

1
UINotificationGenerator仅适用于配备有触觉引擎的设备,即iPhone 7及更高版本。我在我的iPhone 6s上尝试了这段代码,但它没有起作用。我进一步了解了一下,发现它只能在启用了系统设置中的“系统触感”选项的设备上运行,否则它将无法正常工作。 - Lazar Nikolov

6
#import <AudioToolbox/AudioServices.h>


AudioServicesPlayAlertSound(UInt32(kSystemSoundID_Vibrate))

这是Swift函数...请参阅此文章获取详细描述。


这对我不起作用,也许是苹果改变了什么或者我做错了什么?它只会给我一个震动。 - jammyman34

4
这是我想到的内容:
import UIKit
import AudioToolbox

class ViewController: UIViewController {

    var counter = 0
    var timer : NSTimer?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func vibratePhone() {
        counter++
        switch counter {
        case 1, 2:
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        default:
            timer?.invalidate()
        }
    }

    @IBAction func vibrate(sender: UIButton) {
        counter = 0
        timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "vibratePhone", userInfo: nil, repeats: true)
    }
}

当您按下按钮时,计时器开始并在所需的时间间隔内重复。 NSTimer调用vibratePhone(Void)函数,从那里我可以控制手机震动的次数。 在这种情况下,我使用了一个开关,但您也可以使用if else。 只需设置一个计数器以计算每次调用函数的次数。

1
这个可以运行,但是在第一次振动之前会有大约一秒钟的延迟。 - jammyman34

2
如果您只想让设备震动两次,您可以这样做:

```最初的回答```

    func vibrate() {
        AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate) {
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        }
    }

通过使用递归和 AudioServicesPlaySystemSoundWithCompletion,可以实现多次振动。

您可以向振动函数传递一个计数器,如 vibrate(count: 10)。然后它会振动10次。

原始回答:最初的回答

    func vibrate(count: Int) {
        if count == 0 {
            return
        }
        AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate) { [weak self] in
            self?.vibrate(count: count - 1)
        }
    }


如果使用UIFeedbackGenerator,有一个很好的库Haptica


希望这有所帮助。


当您播放音频或进行WebRTC通话时,只有UIFeedbackGenerator起作用。 - famfamfam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接