UI控件
UIButton常用属性
1.1UIButton的创建
a.不带样式的:
let btn: UIButton = UIButton()
b.带样式的:
let btns:UIButton = UIButton(type: UIButtonType)
用法如下:
let btn: UIButton = UIButton(type: .Custom)
1.2UIButton设置字内容和颜色
btn.setTitle("按钮", forState: .Normal) btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
1.3UIButton设置背景颜色和背景图片
btn.backgroundColor = UIColor.blackColor() btn.setBackgroundImage(UIImage(named:"1"), forState: .Normal)
1.4UIButton设置字体大小
btn.titleLabel?.font = UIFont.systemFontOfSize(20)
1.5禁用UIButton
btn.enabled = false //禁止按钮,默认为true
1.6设置圆角
btn.layer.cornerRadius = 8
1.7设置背景图片为圆角(因为我们直接设置UIButton圆角时,图片不会变为圆角)
buttonImage.setImage(UIImage(named:"1") , forState: UIControlState.Normal) //设置背景图片为圆角 buttonImage.imageView?.layer.cornerRadius = 50
1.8在UIButton上添加图片和文字,有时需要我们调整,此时需要:
//方向为逆时针方向,上、左、下、右依次去设置的 btn.imageEdgeInsets = UIEdgeInsetsMake(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) btn.titleEdgeInsets = UIEdgeInsetsMake(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat)
案例:
//创建一个图片一个文字的按钮 let btn2: UIButton = UIButton(type: .Custom) btn2.frame = CGRectMake(50, 100, 120, 35) btn2.setImage(UIImage(named: "1"), forState: .Normal) btn2.backgroundColor = UIColor.blackColor() btn2.titleLabel?.font = UIFont.systemFontOfSize(20) btn2.imageView?.contentMode = UIViewContentMode.ScaleAspectFit btn2.setTitle("图片按钮", forState: .Normal) //偏移量,分别为上下左右 btn2.imageEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0) btn2.titleEdgeInsets = UIEdgeInsetsMake(0, -80, 0, 5) btn2.setTitleColor(UIColor.whiteColor(), forState: .Normal) btn2.adjustsImageWhenHighlighted = false self.view.addSubview(btn2)
如图:
1.9添加按钮的点击事件
//第一种是不带参数的,第二种是带参数的 btn.addTarget(self, action:"click", forControlEvents: .TouchUpInside) btn.addTarget(self, action:"clicks:", forControlEvents: .TouchUpInside) //第一种: func click(){} //第二种: func clicks(sender:UIButton){}
1.10按钮带边框
Btn.layer.borderColor = UIColor.blackColor().CGColor
案例:
let Btn = UIButton(.Custom) Btn.frame = CGRect(x:0,y:0,width:50,height:20) Btn.setTitle("边框按钮", forState: .Normal) Btn.setTitleColor(UIColor.blackColor(), forState: .Normal) Btn.layer.borderColor = UIColor.blackColor().CGColor Btn.layer.borderWidth = 1 Btn.layer.cornerRadius = 8 Btn.layer.masksToBounds = true self.view.addSubview(btn6)
如图: