asyncAfter 不延迟指定时间的第一次执行

asyncAfter not delaying the first execution by specified time

我正在尝试为文本视图制作动画,让字符串字符一个接一个地出现,然后在 0.5 秒延迟后从第一个字符开始一个接一个地消失。

我很接近,我遇到的唯一问题是第一个字符会立即被删除,所以就好像它从未出现过一样。任何想法,这是我的功能:

extension UITextView {

    func animate(newText: String) {

        DispatchQueue.main.async {

            self.text = ""

            for (index, character) in newText.enumerated() {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 * Double(index)) {
                    self.text?.append(character)
                }

                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 * Double(index)) {
                    self.text?.remove(at: newText.startIndex)
                }
            }
        }
    }
}

问题在于第一个字符的索引为 0,因此延迟为 .now() + 0.5 * 0,这简化为 .now()

给延迟加一个常量:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 * Double(index) + 0.5) {
                                                                    ^^^^^^

这将导致第一个字符在 1 秒后消失。

或者:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 * Double(index + 1)) {

此外,如果您的文本很长,在这里使用 Timer 可能更合适,正如 Rob 在评论中所说的那样。

var index = 0
let characterArray = Array(newText)

Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
    textView.text! += "\(characterArray[index])"
    index += 1
    if index == characterArray.endIndex {
        timer.invalidate()
    }
}