如何在另一个之前执行dispatchQueue.main块。斯威夫特3

时间:2017-07-19 21:06:53

标签: swift grand-central-dispatch

在DispatchQueue.main中的动画播放时,我的应用没有响应,我知道这是由于主线程被阻止。有没有办法解决这个问题

DispatchQueue.main.async {
    self.alert(text: "Hello")
}

我的动画需要6秒,因此应用程序没有响应时间很长。

我的动画:

func alert(text: String){
    let alert = UILabel()

    alert.frame.origin = CGPoint(x: 0, y: -90)
    alert.frame.size.width = self.view.frame.width
    alert.frame.size.height = 45
    alert.layer.backgroundColor = UIColor(red: 114/255, green: 217/255, blue: 161/255, alpha: 0.99).cgColor
    alert.text = "\(text)"
    alert.textColor = .white
    alert.textAlignment = .center
    alert.lineBreakMode = .byWordWrapping // or NSLineBreakMode.ByWordWrapping
    alert.numberOfLines = 0
    alert.font = UIFont (name: "HelveticaNeue-Thin", size: 17)
    alert.textColor = .white
    alert.layer.borderColor = UIColor(red: 100/255, green: 203/255, blue: 147/255, alpha: 0.95).cgColor
    alert.layer.borderWidth = 2
    alert.clipsToBounds = true
    view.addSubview(alert)

    UIView.animate(withDuration: 0.2, animations: {
        alert.frame.origin = CGPoint(x: 0, y: -45)
        self.view.frame.origin.y = 45
    }) { (true) in
        UIView.animate(withDuration: 0.2, delay: 5, animations: {
            alert.frame.origin = CGPoint(x: 0, y: -90)
            self.view.frame.origin.y = 0
        })
    }
}

2 个答案:

答案 0 :(得分:1)

如果您使用的是UIView.animate,则可以通过设置allowUserInteraction动画选项来使应用程序响应

torch[cpuType]

答案 1 :(得分:0)

您可以使用

DispatchQueue.main.asyncAfter(deadline: .now() + delay) {}

甚至是UIView动画。

UIView.animate(withDuration: 2.0, animations: { 
        //show loading
    }) { (completed) in
        //hide loading
    }

感谢@rmaddy的建议