async之后不延迟指定时间的第一次执行



我正在尝试对文本视图进行动画处理以使字符串字符一个接一个地出现,然后在 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()
    }
}

最新更新