UIView Swift倾斜动画 [英] UIView Swift Tilting Animation

查看:185
本文介绍了UIView Swift倾斜动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIImageView,我想让它在我调用一个函数时,图像从平坦状态(正常状态)变为向右旋转(例如旋转20度),然后返回

I have an UIImageView and I would like it so that when I call a function, the image goes from flat(the normal state), to a tilting to the right rotation(say maybe a 20 degree rotation), then back to it's flat(normal) state.

此是我目前拥有的,但是我无法获得理想的结果。

This is what I currently have, but I can't get the desired outcome.

extension UIView {

    func rotate(duration: CFTimeInterval = 2) {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.fromValue = 0.0
        rotateAnimation.toValue = CGFloat(20)
        rotateAnimation.isRemovedOnCompletion = true
        rotateAnimation.duration = duration
        rotateAnimation.repeatCount=Float.infinity
        self.layer.add(rotateAnimation, forKey: nil)
    }

}

UIImageView.rotate()


推荐答案

我尝试过创建上述动画,并且我尝试过的代码在这里

I tried Creating the above Animation and my tried code Is here

必需的声明

///View Outlet - Image or UIView
@IBOutlet weak var baseView: UIImageView!

/// Timer - To make Animation in repititive State
var newNAimationTimer : Timer?    

/// Plus Degree
let degrees : CGFloat = 20.0
/// Minus Degree
let minusDegree : CGFloat = -20.0

定时器功能

//MARK: Start Timer
    func startTimer()
    {
        /// Start timer if Timer is Not Initialised Before
        if newNAimationTimer == nil {
            /// Assign Timer
            newNAimationTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(animationVC.animateView), userInfo: nil, repeats: true)
        }
    }

    //MARK: Stop Timer
    func stopTimer()
    {
        ///Check Do timer is Initialised
        if newNAimationTimer != nil {
            /// Yes Stop
            newNAimationTimer?.invalidate()
        }
    }

计时器处理程序

/// Animate View With Animations
    @objc func animateView()
    {
        let plusRadian : CGFloat = degrees * CGFloat((Double.pi/180))
        let minusRadian : CGFloat = minusDegree * CGFloat((Double.pi/180))

        /// First Animation To make View Goes clockwise
        UIView.animate(withDuration: 0.5, animations: {
             self.baseView.transform = CGAffineTransform(rotationAngle: plusRadian)
        }) { (success) in
            /// Second Animation to make view go antiClockWise
            UIView.animate(withDuration: 0.5, animations: {
                self.baseView.transform = CGAffineTransform(rotationAngle: minusRadian)
            })
        }
    }

按钮操作

@IBAction func animationButton(_ sender: Any) {
        /// Start the Animation
        startTimer()
    }

ScreenShots

首先:

第二个:

Second:

运行输出

这篇关于UIView Swift倾斜动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆