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()//將圖像視圖從父視圖中移除
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章