2017-07-19 73 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

試過了,它不工作抱歉 –

相關問題