当我点击一个按钮时,我搜索让我的 iPhone 振动两次(如短信提醒振动)
我AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
只获得一次正常振动,但我想要两条短裤:/。
当我点击一个按钮时,我搜索让我的 iPhone 振动两次(如短信提醒振动)
我AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
只获得一次正常振动,但我想要两条短裤:/。
iOS 10 更新
在 iOS 10 中,有一些新方法可以用最少的代码做到这一点。
方法 1 - UIImpactFeedbackGenerator:
let feedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
feedbackGenerator.impactOccurred()
方法 2 - UINotificationFeedbackGenerator:
let feedbackGenerator = UINotificationFeedbackGenerator()
feedbackGenerator.notificationOccurred(.error)
方法 3 - UISelectionFeedbackGenerator:
let feedbackGenerator = UISelectionFeedbackGenerator()
feedbackGenerator.selectionChanged()
#import <AudioToolbox/AudioServices.h>
AudioServicesPlayAlertSound(UInt32(kSystemSoundID_Vibrate))
这是 swift 功能……详细说明见这篇文章。
这就是我想出的:
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。只需在每次调用函数时设置一个计数器进行计数。
如果您只想振动两次。你可以只是..
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
希望能帮助到你。