一、内容概要
按钮是所有UI体系中非常重要的组件,在iOS中按钮UIButton的使用也非常灵活,本文将从以下几点介绍UIButton的使用(基于Swift2.0):
1.UIButton基础
2.UIButton图片使用
3.圆角按钮
4.复选框按钮
5.倒计时按钮(闪烁问题也轻松解决)
6.贪婪按钮(父控件事件也归我,扩大事件响应区域)
二、UIButton基础
2.1创建
UIButton提供了一个简单的构造方法
convenience init(type buttonType: UIButtonType)
此方法中需要我们传入一个UIButtonType枚举类型,使用代码如下:
func createButton() {
let button = UIButton(type: UIButtonType.System)
button.frame = CGRectMake(50, 50, 100, 50)
button.setTitle("确定", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func buttonPressed(button: UIButton) {
}
Tips:
1.设置按钮标题时,一定要通过
func setTitleColor(color: UIColor?, forState state: UIControlState)
不可通过
button.titleLabel?.text = "确定"
此方式会在点击时标题自动变为setTitleColor方法Normal状态下的文字
2.2图片使用
UIButton提供了以下两个接口使用图片:
func setImage(image: UIImage?, forState state: UIControlState)
func setBa