簡體   English   中英

asyncAfter 不延遲指定時間的第一次執行

[英]asyncAfter not delaying the first execution by specified time

我正在嘗試為 textview 設置動畫以使字符串字符一個一個出現,然后在 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()
    }
}

暫無
暫無

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

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