【发布时间】:2015-04-24 05:00:40
【问题描述】:
当我点击一个按钮时,我会搜索让我的 iPhone 振动两次(比如短信提醒振动)
与AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
我只获得了一次正常振动,但我想要两条短裤:/。
【问题讨论】:
标签: ios swift iphone-vibrate
当我点击一个按钮时,我会搜索让我的 iPhone 振动两次(比如短信提醒振动)
与AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
我只获得了一次正常振动,但我想要两条短裤:/。
【问题讨论】:
标签: ios swift iphone-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函数……详细说明见this文章。
【讨论】:
这是我想出的:
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
希望对你有帮助。
【讨论】: