码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-12-15 00:49:39      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:res   hup   lin   action   port   toms   highlight   events   大小   

效果如图:

技术分享图片

代码如下:

//
//  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
        }
    }
}

素材:

技术分享图片技术分享图片 

 

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

标签:res   hup   lin   action   port   toms   highlight   events   大小   

原文地址:http://www.cnblogs.com/Dast1/p/8038837.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!