Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 在数组中循环时是否有方法包含定时暂停?_Swift_Xcode - Fatal编程技术网

Swift 在数组中循环时是否有方法包含定时暂停?

Swift 在数组中循环时是否有方法包含定时暂停?,swift,xcode,Swift,Xcode,我正在创建一个应用程序,可以将字符串中的字母转换为振动模式。以下是我到目前为止的情况: @IBAction func translateButtonTapped(_ sender: UIButton) { guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else {return} let Bz1 = CHHapticEvent(eventType: .hapticContinuous, parameters:

我正在创建一个应用程序,可以将字符串中的字母转换为振动模式。以下是我到目前为止的情况:

@IBAction func translateButtonTapped(_ sender: UIButton) {
   guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else {return}

let Bz1 = CHHapticEvent(eventType: .hapticContinuous, parameters: [], relativeTime: 0.0, duration: 0.1)
let Bz2 = CHHapticEvent(eventType: .hapticContinuous, parameters: [], relativeTime: 0.3, duration: 0.1)
let Bzz1 = CHHapticEvent(eventType: .hapticContinuous, parameters: [], relativeTime: 0.0, duration: 0.25)

let dictionary = [
"A" : [Bzz1],
"T" : [Bz1, Bz2],
]

let message = detectedTextLabel.text
//text box where string is written

let letterArray = message!.map { String($0) }

 for singleWord in letterArray {

    let word = String(singleWord)
    if let vibrationArray = dictionary[word] {

    do {

      for Word in vibrationArray {

           let encodedMessage = try CHHapticPattern(events: [Word], parameters: [])
           let player = try engine?.makePlayer(with: encodedMessage)
           try player?.start(atTime: 0)

    }
     } catch {
       print("there was an error")
     }

     } else {
      print("There was an error")
      }

 }


到目前为止,如果我在文本框中键入单数字母,则此代码有效。然而,作为一个例子,如果我在文本框中键入“AT”,而不是振动一个接一个地播放,它们会同时播放。有没有办法在第一个字母模式和第二个字母模式之间设置某种延迟或暂停?

我会将其从for…in循环转换为传统的C样式for循环,以便跟踪索引。然后,当进入for循环时,可以根据当前的字母索引将所有内容包装在DispatchQueue延迟中。像这样的

for i in 0..<letterArray.count {
    DispatchQueue.main.asyncAfter(deadline: .now() + Double(i*1)) {
        // put current for loop code inside here
    }
}

使用定时器进行延迟

Timer.scheduledTimer(withTimeInterval:1,repeats:false){in//Do your stuff here}

您尝试过sleep()函数吗?我尝试过。它出现了一个错误,说CHHapticEvent与睡眠函数不兼容请尝试以下操作:Timer.scheduledTimer(withTimeInterval:1,repeats:false){{in//Do your stuff here}这正是我所需要的!非常感谢!很高兴能帮忙!列举的方法可能最适合你的情况,我只是没有马上想到。
for (index, singleWord) in letterArray.enumerated() {
    DispatchQueue.main.asyncAfter(deadline: .now() + Double(index * 1)) {
        // put current for loop code inside here
    }
}