1.创建系统自带按钮
let btn = UIButton(type: .contactAdd)
btn.frame = CGRect(x: 100, y: 105, width: 30, height: 30)
self.view.addSubview(btn)
/*
UIButtonType.type有以下几种:
system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效
infoDark:为感叹号“!”圆形按钮UIButtonType.infoLight:为感叹号“!”圆形按钮
*/
2.创建自定义按钮
let rect = CGRect(x: 200, y: 100, width: 100, height: 40)
let button = UIButton(frame: rect)
//设置按钮的文字
button.setTitle("点击", for: .normal)
self.view.addSubview(button)
3.修改按钮样式
//设置按钮标题样式
button.titleLabel?.font = UIFont(name: "Arial", size: 20)
//设置背景颜色
button.backgroundColor = UIColor.yellow
//设置背景图片
let bgImage = UIImage(named: "image1")
button.setBackgroundImage(bgImage, for: .normal)
//设置圆角
button.layer.masksToBounds = true
button.layer.cornerRadius = 5
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.blue.cgColor
4.设置按钮在不同状态下的样式
button.setTitle("点击", for: .normal) //正常状态下文字
button.setTitle("正在点击", for: .highlighted) //高亮时文字
button.setTitle("获得焦点", for: .focused) //获取焦点时文字
button.setTitle("按钮不可用", for: .disabled) //不可用时文字
button.setTitle("按钮已选中", for: .selected) //选中时文字
button.setTitleColor(UIColor.red, for: .normal) //正常时标题颜色
button.setTitleColor(UIColor.darkGray, for: .selected) //选中时标题颜色
5.为按钮添加点击事件
//是否禁止按钮使用
button.isEnabled = true //true:可用(默认);false:禁止
//添加事件
button.addTarget(self, action: #selector(ViewController.buttonClick(_:)), for: UIControlEvents.touchUpInside)
//点击事件处理方法
func buttonClick(_ button:UIButton)
{
NSLog("Button TouchInSide")
}
效果如果所示: