簡體   English   中英

點擊按鈕后如何使我的iphone振動兩次?

[英]How to make my iphone vibrate twice when I click on a button?

當我點擊一個按鈕(就像一個短信警報振動)時,我搜索我的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))

這是快速功能...有關詳細說明,請參閱文章。

這就是我想出的:

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


希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM