使用 UIView 的 animateWithDuration

作者: CaiYue_ | 来源:发表于2016-09-18 16:25 被阅读2579次

    本文是《巧用UIView辅助开发》文集的第二篇,从最简单的UIView开始,学习iOS开发中的一点经验技巧。

    文集第一篇戳 手把手教你如何同时绘制圆角和阴影

    原文链接:http://www.jianshu.com/p/f9ac729758e0

    效果图

    废话少说,先上效果图:

    动画效果动画效果

    demo的源码和图片资源戳 https://github.com/caiyue1993/RolitaCircle

    实现的效果主要使用的是 UIView 的 animateWithDuration 方法。UIView可以通过设置transform属性做变换,但实际上它只是封装了内部图层的变换。

    苹果官方文档中对 animateWithDuration 方法的介绍如图:

    关于animateWithDuration的介绍关于animateWithDuration的介绍

    注意看划线的部分,我们在传给 animations 参数的 block 可以programmatically change any animatable properties of views in your view hierarchy 。翻译成中文就是,我们可以在这个block中对视图中 animatable 的属性进行更改,从而可以产生动画效果。

    至于哪些属性是 animatable 的,只要 command 键点击属性去看即可,如图:

    查看animatable属性查看animatable属性

    使用贝赛尔曲线画圆

    关于贝赛尔曲线在这篇文章中就不介绍了,参见官方文档 UIBezierPath Class Reference

    使用贝赛尔曲线画圆,首先,我们可以建立一个Button的子类(不妨命名成LolitaCircleButton)用来绘制特定颜色的圆按钮(加上阴影),代码如下:

        override func drawRect(rect: CGRect) {
            super.drawRect(rect)
            let path = UIBezierPath(ovalInRect: rect)
            color.setFill()
            path.fill()
        }
    
    

    现在的效果如图所示:

    使用贝赛尔曲线画圆使用贝赛尔曲线画圆

    当我们点击按钮时,给按钮加上缩小的动画效果:

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            super.touchesBegan(touches, withEvent: event)
    
            color = UIColor.whiteColor()
            setNeedsDisplay()
    
            UIView.animateWithDuration(0.15) {
                self.transform = CGAffineTransformMakeScale(0.9, 0.9)
            }
        }
    

    当释放按钮时,加上回收的效果,还是直接上代码吧:

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            super.touchesEnded(touches, withEvent: event)
    
            color = UIColor.orangeColor()
            setNeedsDisplay()
    
            transform = CGAffineTransformMakeScale(0.0, 0.0)
    
            UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
                self.transform = CGAffineTransformIdentity
                // CGAffineTransformIdentity也可替换成CGAffineTransformMakeScale(1.0, 1.0)
                }, completion: nil)
        }
    
    

    然后加上按钮在normal状态和highlighted状态显示的图片。

    func commonInit() {
           setImage(UIImage(named: self.imageURL)?.imageWithColor(self.color), forState: .Highlighted)
           setImage(UIImage(named: self.imageURL), forState: .Normal)
       }
    // 其中imageURL是初始化时外部传入的图片地址
    

    这样,开头的按钮动画就完成了。具体的实现细节,请戳下面的链接。

    Gist 地址: BubblePop

    《巧用UIView辅助开发》系列第二篇就写到这里。

    相关文章

      网友评论

      本文标题:使用 UIView 的 animateWithDuration

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