Swift-按钮(UIButton)的用法(转)

/ Mac / 没有评论 / 1481浏览

Swift-按钮(UIButton)的用法(转)

1,按钮的创建

(1)按钮有下面四种类型:

(注意:自ios7起,infoDark、infoLight、detailDisclosure效果都是一样的) 1

//创建一个ContactAdd类型的按钮
let button:UIButton = UIButton(type:.contactAdd)
//设置按钮位置和大小
button.frame = CGRect(x:10, y:150, width:100, height:30)
//设置按钮文字
button.setTitle("按钮", for:.normal)
self.view.addSubview(button)

(2)对于Custom定制类型按钮,代码可简化为:

let button = UIButton(frame:CGRect(x:10, y:150, width:100, height:30))

2,按钮的文字设置

button.setTitle("普通状态", for:.normal) //普通状态下的文字
button.setTitle("触摸状态", for:.highlighted) //触摸状态下的文字
button.setTitle("禁用状态", for:.disabled) //禁用状态下的文字

3,按钮文字颜色的设置

button.setTitleColor(UIColor.black, for: .normal) //普通状态下文字的颜色
button.setTitleColor(UIColor.green, for: .highlighted) //触摸状态下文字的颜色
button.setTitleColor(UIColor.gray, for: .disabled) //禁用状态下文字的颜色

4,按钮文字阴影颜色的设置

button.setTitleShadowColor(UIColor.green, for:.normal) //普通状态下文字阴影的颜色
button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通状态下文字阴影的颜色
button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通状态下文字阴影的颜色

5,按钮文字的字体和大小设置

button.titleLabel?.font = UIFont.systemFont(ofSize: 11)

6,按钮背景颜色设置

button.backgroundColor = UIColor.black

7,按钮文字图标的设置

默认情况下按钮会被渲染成单一颜色 2

button.setImage(UIImage(named:"icon1"),forState:.Normal)  //设置图标
button.adjustsImageWhenHighlighted=false //使触摸模式下按钮也不会变暗(半透明)
button.adjustsImageWhenDisabled=false //使禁用模式下按钮也不会变暗(半透明)

8,设置按钮背景图片

3

button.setBackgroundImage(UIImage(named:"bg1"), for:.normal)

9,按钮触摸点击事件响应

不传递触摸对象(即点击的按钮)

button.addTarget(self, action:#selector(self.tapped), for:.touchUpInside)
@objc func tapped(){
  print("tapped")
}

传递触摸对象(即点击的按钮),需要在定义action参数时,方法名称后面带上冒号

button.addTarget(self, action:#selector(tapped(button:)) , for:.touchUpInside)
@objc func tapped(button:UIButton){

}

常用的触摸事件类型:

10,按钮文字太长时的处理方法

默认情况下,如果按钮文字太长超过按钮尺寸,则会省略中间的文字。比如下面代码:

let button = UIButton(frame:CGRect(x:20, y:50, width:130, height:50))
button.setTitle("这个是一段 very 长的文字", for:.normal) //普通状态下的文字
button.setTitleColor(UIColor.white, for: .normal) //普通状态下文字的颜色
button.backgroundColor = UIColor.orange
self.view.addSubview(button)

运行效果如下,中间文字使用 ... 代替。 4 我们通过修改 button 按钮中 titleLabel 的 lineBreakMode 属性,便可以调整按钮在文字超长的情况下如何显示,以及是否换行。

//省略尾部文字
button.titleLabel?.lineBreakMode = .byTruncatingTail

lineBreakMode 共支持如下几种样式:

注意:当设置自动换行后(byWordWrapping 或 byCharWrapping),我们可以在设置 title 时通过 \n 进行手动换行。

button.setTitle("欢迎访问\nhangge.com", for:.normal)

11