Xcode9学习笔记61 - 检测UIView视图动画的结束事件
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let rect = CGRect(x: 58, y: 40, width: 200, height: 200) let imageView = UIImageView(frame: rect) let image = UIImage(named: "Pic") imageView.image = image//给图像视图指定要显示的图片 imageView.tag = 1//设置图像视图的标识值,以方便后期对图像视图的调用 self.view.addSubview(imageView) let button = UIButton(type: UIButtonType.system)//初始化一个按钮对象,点击按钮时播放动画 button.frame = CGRect(x: 58, y: 400, width: 200, height: 44) button.backgroundColor = UIColor.lightGray button.setTitle("Tap", for: UIControlState()) button.addTarget(self, action: #selector(ViewController.playAnimation), for: UIControlEvents.touchUpInside) self.view.addSubview(button) } @objc func playAnimation() { UIView.beginAnimations(nil, context: nil)//发出开始动画的请求 UIView.setAnimationCurve(.easeOut)//设置动画的播放速度为淡入淡出 UIView.setAnimationDuration(5)//设置动画时长5秒 UIView.setAnimationBeginsFromCurrentState(true)//设置动画从当前状态开始播放 let view = self.view.viewWithTag(1)//通过标识值找到之前创建的图像视图,作为动画的载体 UIView.setAnimationTransition(.flipFromRight, for: view!, cache: true)//设置动画类型为翻转动画 view?.frame = CGRect(x: 50, y: 50, width: 0, height: 0)//视图翻转时移到目标位置并缩小至不可见 UIView.setAnimationDelegate(self)//设置动画代理对象为当前视图控制器类,动画结束后控制台打印输出日志 UIView.setAnimationDidStop(#selector(ViewController.animationStop))//设置动画结束时执行的方法 UIView.commitAnimations()//调用视图的提交动画方法,标志着动画块的结束 } @objc func animationStop() {//响应动画结束事件 print("Animation Stop.") self.view.viewWithTag(1)?.removeFromSuperview()//将图像视图从父视图中移除 }