问题
This is related to my previous question.
I have the following method where it moves a playing card.
func moveCard() -> Void{
UIView.animate(withDuration: 5.0) {
self.hhview.transform = CGAffineTransform(translationX: -160, y: 0)
} completion: { _ in
print("Move completed")
}
}
This method is called by different parent methods. But the rest of the parent methods are executed before the completion of the transition. For example, playerCheck continued is printed before Move completed.
func playerCheck() -> Void{
......
moveCard()
// how to wait till completion of the transition
print("playerCheck continued")
}
How can I set the parent methods to wait till the transformation is completed before executing the rest of the functionality?
回答1:
Make moveCard accept a completion handler, and put all the code "after" moveCard in the completion handler:
func moveCard(completion: () -> Void) -> Void{
UIView.animate(withDuration: 5.0) {
self.hhview.transform = CGAffineTransform(translationX: -160, y: 0)
} completion: { _ in
print("Move completed")
completion()
}
}
moveCard {
print("playerCheck continued")
}
If you are going to call another method that has a completion handler, in the completion handler, there might be quite a lot of nesting. You might consider using PromiseKit, where you can use then to chain these.
来源:https://stackoverflow.com/questions/65642747/how-to-wait-till-a-uiview-transition-is-over