美文网首页
两个UIView 左右翻转动画

两个UIView 左右翻转动画

作者: 生命不止运动不息 | 来源:发表于2023-02-18 13:37 被阅读0次

    点击翻转两个View, 完整代码如下:

    class ViewController: UIViewController {
        
        let firstView = UIView()
        let secondView = UIView()
        var isFliped = false
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            
            self.view.backgroundColor = .white
            
            let bgView = UIView()
            bgView.backgroundColor = .white
            bgView.frame = .init(x: 0, y: 0, width: 280, height: 180)
            bgView.center = self.view.center
            self.view.addSubview(bgView)
            
            secondView.backgroundColor = .blue
            secondView.frame = bgView.bounds
            bgView.addSubview(secondView)
            
            firstView.backgroundColor = .red
            firstView.frame = bgView.bounds
            bgView.addSubview(firstView)
            
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap))
            self.view.addGestureRecognizer(tap)
        }
        
        @objc func tap() {
            let fromView = isFliped ? self.secondView : self.firstView
            let toView = isFliped ? self.firstView : self.secondView
            let direction: UIView.AnimationOptions = isFliped ? .transitionFlipFromLeft : .transitionFlipFromRight
            
            UIView.transition(from: fromView, to: toView, duration: 0.5, options: direction) { finished in
                if finished {
                    fromView.superview?.sendSubviewToBack(fromView)
                    self.isFliped = !self.isFliped
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:两个UIView 左右翻转动画

          本文链接:https://www.haomeiwen.com/subject/nwhbkdtx.html