Note: Swift Tutorial – Custom UIButton Class (Reusable)

栏目: Swift · 发布时间: 7年前

内容简介:这个入门教程设计了一个自定义的

Swift Tutorial – Custom UIButton Class (Reusable)

这个入门教程设计了一个自定义的 Button ,基于 UIButton 类,设置了按钮背景色、标题字体和大小,并设置了阴影,同时提供了抖动的动画效果。

初始化

init(frame: CGRect) 是用于代码创建按钮的初始化,而 init?(coder aDecoder: NSCoder) 是用于 StoryBoard 拖拽出来的按钮的初始化。

按钮抖动效果

只需设置动画起始和结束位置、动画次数和耗时,通过 CABasicAnimation 就可以实现抖动效果,示例代码实现的是左右抖动效果。

自定义按钮类代码实现

源码取自源教程的提供的 DropBox 下载。

class CustomButton: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupButton()
    }
    
    func setupButton() {
        setShadow()
        setTitleColor(.white, for: .normal)
        
        backgroundColor      = Colors.coolBlue
        titleLabel?.font     = UIFont(name: "AvenirNext-DemiBold", size: 18)
        layer.cornerRadius   = 25
        layer.borderWidth    = 3.0
        layer.borderColor    = UIColor.darkGray.cgColor
    }
    
    private func setShadow() {
        layer.shadowColor   = UIColor.black.cgColor
        layer.shadowOffset  = CGSize(width: 0.0, height: 6.0)
        layer.shadowRadius  = 8
        layer.shadowOpacity = 0.5
        clipsToBounds       = true
        layer.masksToBounds = false
    }
    
    func shake() {
        let shake           = CABasicAnimation(keyPath: "position")
        shake.duration      = 0.1
        shake.repeatCount   = 2
        shake.autoreverses  = true
        
        let fromPoint       = CGPoint(x: center.x - 8, y: center.y)
        let fromValue       = NSValue(cgPoint: fromPoint)
        
        let toPoint         = CGPoint(x: center.x + 8, y: center.y)
        let toValue         = NSValue(cgPoint: toPoint)
        
        shake.fromValue     = fromValue
        shake.toValue       = toValue
        
        layer.add(shake, forKey: "position")
    }   
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Analytics

Web Analytics

Avinash Kaushik / Sybex / 2007-6-5 / USD 29.99

在线阅读本书 Written by an in-the-trenches practitioner, this step-by-step guide shows you how to implement a successful Web analytics strategy. Web analytics expert Avinash Kaushik, in his thought-p......一起来看看 《Web Analytics》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具