1,按鈕的創建
(1)按鈕有下面四種類型:
contactAdd:前面帶“+”圖標按鈕,默認文字顏色為藍色,有觸摸時的高亮效果 detailDisclosure:前面帶“!”圖標按鈕,默認文字顏色為藍色,有觸摸時的高亮效果 system:前面不帶圖標,默認文字顏色為藍色,有觸摸時的高亮效果 custom:定制按鈕,前面不帶圖標,默認文字顏色為白色,無觸摸時的高亮效果 infoDark:為感嘆號“!”圓形按鈕 infoLight:為感嘆號“!”圓形按鈕
//創建一個ContactAdd類型的按鈕 let button:UIButton = UIButton(type:.custom) //設置按鈕位置和大小 button.frame=CGRect(x:50,y:180,width:self.view.bounds.size.width - 100,height:50) //設置按鈕文字 button.setTitle("按鈕", for: .normal) self.view.addSubview(button);
(2)對於Custom定制類型按鈕,代碼可簡化為:
let btn = CGRect(x:100,y:200,width:80,height:50)
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.backgroundColor=UIColor.black
6,按鈕文字圖標的設置
button.setImage(UIImage(named:"icon1"),for:.normal) //設置圖標 button.adjustsImageWhenHighlighted=false //使觸摸模式下按鈕也不會變暗 button.adjustsImageWhenDisabled=false //使禁用模式下按鈕也不會變暗
7,設置按鈕背景圖片
button.setBackgroundImage(UIImage(named:"background1"),for:.normal)
8,按鈕觸摸點擊事件響應
//不傳遞觸摸對象(即點擊的按鈕) button.addTarget(self,action:#selector(tapped),for:.touchUpInside) func tapped(){ print("tapped") } //傳遞觸摸對象(即點擊的按鈕),需要在定義action參數時,方法名稱后面帶上冒號 button.addTarget(self,action:#selector(tapped(_button:)),for:.touchUpInside) func tapped(_button:UIButton){ }
常用的觸摸事件類型:
touchDown:單點觸摸按下事件,點觸屏幕
touchDownRepeat:多點觸摸按下事件,點觸計數大於1,按下第2、3或第4根手指的時候
touchDragInside:觸摸在控件內拖動時
touchDragOutside:觸摸在控件外拖動時
touchDragEnter:觸摸從控件之外拖動到內部時
touchDragExit:觸摸從控件內部拖動到外部時
touchUpInside:在控件之內觸摸並抬起事件
touchUpOutside:在控件之外觸摸抬起事件
touchCancel:觸摸取消事件,即一次觸摸因為放上太多手指而被取消,或者電話打斷
9.我們通過修改button按鈕中的titleLabel的lineBreakMode屬性,遍可以調整按鈕在文字超長的情況下如何顯示,以及是否換行
case byWordWrapping // Wrap at word boundaries, default 自動換行,按詞拆分 case byCharWrapping // Wrap at character boundaries 自動換行,按字符拆分 case byClipping // Simply clip 直接將多余的部分截斷 case byTruncatingHead // Truncate at head of line: "...wxyz" case byTruncatingTail // Truncate at tail of line: "abcd..." case byTruncatingMiddle // Truncate middle of line: "ab...yz"
換行符:/n