当我点击一个按钮(就像一个短信警报振动)时,我搜索我的iphone振动两次
使用AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
我只获得一次正常振动,但我想要两条短裤:/。
#import <AudioToolbox/AudioServices.h>
AudioServicesPlayAlertSound(UInt32(kSystemSoundID_Vibrate))
这是快速功能...有关详细说明,请参阅this文章。
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 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
希望能帮助到你。