How to wait till a UIView transition is over

有些话、适合烂在心里 提交于 2021-01-29 09:48:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!