1.按鈕的創建
(1)按鈕有下面四種類型:
UIButtonType.system:前面不帶圖標,默認文字顏色為藍色,有觸摸時的高亮效果
UIButtonType.custom:定制按鈕,前面不帶圖標,默認文字顏色為白色,無觸摸時的高亮效果
UIButtonType.contactAdd:前面帶“+”圖標按鈕,默認文字顏色為藍色,有觸摸時的高亮效果
UIButtonType.detailDisclosure:前面帶“!”圖標按鈕,默認文字顏色為藍色,有觸摸時的高亮效果
UIButtonType.infoDark:為感嘆號“!”圓形按鈕
UIButtonType.infoLight:為感嘆號“!”圓形按鈕
(2)創建一個ContactAdd類型的按鈕
let button:UIButton = UIButton(type:.contactAdd)
2.設置按鈕位置和大小
button.frame = CGRect(x:10, y:150, width:100, height:30)
(1)設置按鈕文字 button.setTitle("按鈕", for:.normal) self.view.addSubview(button)
(2)對于Custom定制類型按鈕,代碼可簡化為: let button = UIButton(frame:CGRect(x:10, y:150, width:100, height:30))
3.按鈕的文字設置
button.setTitle("普通狀態", for:.normal) //普通狀態下的文字
button.setTitle("觸摸狀態", for:.highlighted) //觸摸狀態下的文字
button.setTitle("禁用狀態", for:.disabled) //禁用狀態下的文字
4.按鈕文字顏色的設置
button.setTitleColor(UIColor.black, for: .normal) //普通狀態下文字的顏色
button.setTitleColor(UIColor.green, for: .highlighted) //觸摸狀態下文字的顏色
button.setTitleColor(UIColor.gray, for: .disabled) //禁用狀態下文字的顏色
5.按鈕文字陰影顏色的設置
button.setTitleShadowColor(UIColor.green, for:.normal) //普通狀態下文字陰影的顏色
button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通狀態下文字陰影的顏色
button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通狀態下文字陰影的顏色
6.按鈕背景顏色設置
button.backgroundColor = UIColor.black
7.按鈕文字圖標的設置
(1)默認情況下按鈕會被渲染成單一顏
button.adjustsImageWhenHighlighted=false //使觸摸模式下按鈕也不會變暗(半透明)
button.adjustsImageWhenDisabled=false //使禁用模式下按鈕也不會變暗(半透明)
(2)也可以設置成保留圖標原來的顏色
button.setImage(iconImage, for:.normal) //設置圖標
button.adjustsImageWhenHighlighted = false //使觸摸模式下按鈕也不會變暗(半透明)
button.adjustsImageWhenDisabled = false //使禁用模式下按鈕也不會變暗(半透明)
8.設置按鈕背景圖片
button.setBackgroundImage(UIImage(named:"bg1"), for:.normal)
9.按鈕觸摸點擊事件響應
//不傳遞觸摸對象(即點擊的按鈕)
button.addTarget(self, action:#selector(tapped), for:.touchUpInside)
func tapped(){
print("tapped")
}
//傳遞觸摸對象(即點擊的按鈕),需要在定義action參數時,方法名稱后面帶上冒號
button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside)
func tapped(_ button:UIButton){
print(button.title(for: .normal))
}