点击按钮每次都能实现图片的旋转和切换

Posted Dast1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了点击按钮每次都能实现图片的旋转和切换相关的知识,希望对你有一定的参考价值。

效果如图:

代码如下:

//
//  ViewController.swift
//  TwoSidedView
//
//  Created by mayl on 2017/12/14.
//  Copyright © 2017年. 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
        }
    }
}

素材:

 

 

以上是关于点击按钮每次都能实现图片的旋转和切换的主要内容,如果未能解决你的问题,请参考以下文章

谁能提供一段按钮切换窗口的纯CSS代码?

Bootstrap轮播图的切换按钮如何制作?

图片左右按钮切换滚动的框架怎么做?

css中我有多张图片,我要实现点击一下旁边的按钮就移动一张图片,要左右都可以移动的。请高手指点!

使用导航架构操作点击返回按钮时如何避免片段重新创建?

WPF主窗口按下按钮,关闭当前窗口,切换到另一窗口