2017-07-19 72 views
1

我的应用程序在DispatchQueue.main中的动画播放时没有反应,我知道这是由于主线程被阻止。有没有办法解决这个问题如何在另一个之前执行dispatchQueue.main块。 Swift 3

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 
     }) 
    } 
} 
+0

更新的代码导致你的问题的问题。 – rmaddy

+0

已更新@rmaddy –

+0

目前尚不清楚你的问题是什么。您的动画只需要0.4秒,中间有5秒延迟。 – rmaddy

回答

0

您可以使用

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

甚至一个UIView动画。

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

感谢@rmaddy您的建议

+1

不要使用'performSelector'。这是DispatchQueue的一个非常糟糕的替代品。 – rmaddy

+0

你是对的,更新了答案。 – ppinho

1

如果您正在使用UIView.animate,你可以让你的应用程序响应通过设置的allowUserInteraction动画选项

UIView.animate(withDuration: 6.0, delay: 0, options: .allowUserInteraction, animations: { 

//your animation code 

}, completion: nil) 
+0

试过了,它不工作抱歉 –

相关问题