检索下一个文本时,字符串字母动画会变得混乱

时间:2019-04-14 17:14:44

标签: ios swift

我有一个弹出窗口,该弹出窗口应按字母动画显示用户说明。问题是,只要用户单击“下一个”,字母就会与前一个文本混淆。

动画代码:

extension UILabel {
    func animate(newText: String, characterDelay: TimeInterval) {
        DispatchQueue.main.async {
            self.text = ""

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

按钮操作/调用方法(如您所见,每次用户单击“下一步”时,我都尝试清空变量,但没有成功)

@IBAction func nextbtt(_ sender: Any) {
    var instructions = ["text"]
    counter = counter + 1
    var w1 = " لكن الوصول إليه يتطلب مواجهة وحل تحديات مختلفة"
    var w2 = "هل بإمكانك مساعدتي  في الحصول على الكنز؟"

    let userId = UserDefaults.standard.object(forKey: "userId") as? String
    ref = Database.database().reference()
    let  userLang = ref.child("users").child(userId!).child("lang")
    userLang.observeSingleEvent(of: .value, with: { (snapshot) in
        let lang = snapshot.value as? Int
        if(lang==1){
            ////////////// if user's langague is English
             w1 = "But finding it requires confronting and solving different challenges"
             w2 = " Could you help me in getting the treasure"            }

        instructions.append(w1)
        instructions.append(w2)

        if(self.intrCounter < 3){
            self.mytext.text = ""

            var new = instructions[self.intrCounter]

            self.mytext.text = new

            self.mytext.animate(newText: new ?? "May the source be with you", characterDelay: 0.1)
            self.intrCounter = self.intrCounter + 1

            if(self.intrCounter == 3){
                if(lang==1){
                    (sender as AnyObject).setBackgroundImage(UIImage(named: "engready"), for: UIControl.State.normal)
                }
                else {
                    (sender as AnyObject).setBackgroundImage(UIImage(named: "ready"), for: UIControl.State.normal)}
            }
        }
        else{
        }
    })

    if ( counter == 4){
        status[0] = true
        popUp.removeFromSuperview()
    }
}

屏幕截图:

一个:text is showing to the user, user clicks "next" at the middle of the animation

二:when user clicks next before text 1 is complete 代码:

1 个答案:

答案 0 :(得分:0)

之所以会出现此问题,是因为您正在为每个字符调用一个异步块,并且每个字符可能需要花费更多的时间。 只是为了测试一下,请尝试此更改,如果它有助于相应地更改代码:

var someCounter = 1

extension UILabel {
    func animate(newText: String, characterDelay: TimeInterval) {
        DispatchQueue.main.async {
            self.text = ""

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

让我知道这是否确实是问题所在,如果是的话,我将上传更优化的代码。