效果如图:
代码如下:
// // ViewController.swift // TwoSidedView // // Created by mayl on 2017/12/14. // Copyright ? 2017年 huatu. All rights reserved. // import UIKit let gBtn = UIButton.init(type: UIButtonType.custom) let gImgV4BottomSide = UIImageView.init(image: UIImage.init(named: "bottomSide")) let gImgV4TopSide = UIImageView.init(image: UIImage.init(named: "topSide")) var lBool4ChangeImgV : Bool = false class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setUpUI() } func setUpUI() { view.addSubview(gBtn) gBtn.addTarget(self, action: #selector(ViewController.btnDidClick), for: UIControlEvents.touchUpInside) gBtn.center = view.center gBtn.addSubview(gImgV4BottomSide) gBtn.layer.transform = CATransform3DMakeRotation(CGFloat(Double.pi), 0, 1, 0) gBtn.addSubview(gImgV4TopSide) //按钮大小设置为与图片大小一致 gBtn.bounds = gImgV4BottomSide.bounds } @objc func btnDidClick() { let lAni = CAKeyframeAnimation.init(keyPath: "transform.rotation.y") lAni.duration = 1 lAni.values = [0, Double.pi]; //使得动画结束后,保持动画效果 lAni.isRemovedOnCompletion= false lAni.fillMode = kCAFillModeForwards lAni.delegate = self; gBtn.layer.add(lAni, forKey: nil) } } extension UIViewController: CAAnimationDelegate{ public func animationDidStart(_ anim: CAAnimation) { let lDur:CFTimeInterval = anim.duration DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + lDur * 0.5) { gBtn.bringSubview(toFront: lBool4ChangeImgV == false ? gImgV4BottomSide : gImgV4TopSide) lBool4ChangeImgV = !lBool4ChangeImgV } } }
素材: