Swift3 - xcode按鈕(UIButton)的用法 2016-11-13
1. 按鈕的創(chuàng)建
(1)按鈕有下面四種類型:
UIButtonType.system:前面不帶圖標捅伤,默認文字顏色為藍色做鹰,有觸摸時的高亮效果
UIButtonType.custom:定制按鈕,前面不帶圖標,默認文字顏色為白色我抠,無觸摸時的高亮效果
UIButtonType.contactAdd:前面帶“+”圖標按鈕逼蒙,默認文字顏色為藍色深滚,有觸摸時的高亮效果
UIButtonType.detailDisclosure:前面帶“!”圖標按鈕游昼,默認文字顏色為藍色,有觸摸時的高亮效果
UIButtonType.infoDark:為感嘆號“!”圓形按鈕
UIButtonType.infoLight:為感嘆號“!”圓形按鈕
//創(chuàng)建一個ContactAdd類型的按鈕 let button:UIButton = UIButton(type:.contactAdd) //設(shè)置按鈕位置和大小 button.frame = CGRect(x:10, y:150, width:100, height:30) //設(shè)置按鈕文字 button.setTitle("按鈕", for:.normal) self.view.addSubview(button)
(2)對于Custom定制類型按鈕遗菠,代碼可簡化為:
let button = UIButton(frame:CGRect(x:10, y:150, width:100, height:30))
2 按鈕的文字設(shè)置
button.setTitle("普通狀態(tài)", for:.normal) //普通狀態(tài)下的文字 button.setTitle("觸摸狀態(tài)", for:.highlighted) //觸摸狀態(tài)下的文字 button.setTitle("禁用狀態(tài)", for:.disabled) //禁用狀態(tài)下的文字
3 按鈕文字顏色的設(shè)置
button.setTitleColor(UIColor.black, for: .normal) //普通狀態(tài)下文字的顏色 button.setTitleColor(UIColor.green, for: .highlighted) //觸摸狀態(tài)下文字的顏色 button.setTitleColor(UIColor.gray, for: .disabled) //禁用狀態(tài)下文字的顏色
4 按鈕文字陰影顏色的設(shè)置
button.setTitleShadowColor(UIColor.green, for:.normal) //普通狀態(tài)下文字陰影的顏色 button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通狀態(tài)下文字陰影的顏色 button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通狀態(tài)下文字陰影的顏色
5 按鈕背景顏色設(shè)置
button.backgroundColor = UIColor.black
6 按鈕文字圖標的設(shè)置
(1)默認情況下按鈕會被渲染成單一顏色
button.setImage(UIImage(named:"icon1"),forState:.Normal) //設(shè)置圖標 button.adjustsImageWhenHighlighted=false //使觸摸模式下按鈕也不會變暗(半透明) button.adjustsImageWhenDisabled=false //使禁用模式下按鈕也不會變暗(半透明)
(2)也可以設(shè)置成保留圖標原來的顏色
let iconImage = UIImage(named:"icon2")?.withRenderingMode(.alwaysOriginal) button.setImage(iconImage, for:.normal) //設(shè)置圖標 button.adjustsImageWhenHighlighted = false //使觸摸模式下按鈕也不會變暗(半透明) button.adjustsImageWhenDisabled = false //使禁用模式下按鈕也不會變暗(半透明)
7 設(shè)置按鈕背景圖片
button.setBackgroundImage(UIImage(named:"bg1"), for:.normal)
8 按鈕觸摸點擊事件響應(yīng)
// 不傳遞觸摸對象(即點擊的按鈕) button.addTarget(self, action:#selector(tapped), for:.touchUpInside) func tapped(){ print("tapped") } // 傳遞觸摸對象(即點擊的按鈕)联喘,需要在定義action參數(shù)時华蜒,方法名稱后面帶上冒號 button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside) func tapped(_ button:UIButton){ print(button.title(for: .normal)) }
常用的觸摸事件類型:touchDown:單點觸摸按下事件,點觸屏幕
touchDownRepeat:多點觸摸按下事件豁遭,點觸計數(shù)大于1叭喜,按下第2、3或第4根手指的時候
touchDragInside:觸摸在控件內(nèi)拖動時
touchDragOutside:觸摸在控件外拖動時
touchDragEnter:觸摸從控件之外拖動到內(nèi)部時
touchDragExit:觸摸從控件內(nèi)部拖動到外部時
touchUpInside:在控件之內(nèi)觸摸并抬起事件
touchUpOutside:在控件之外觸摸抬起事件
touchCancel:觸摸取消事件蓖谢,即一次觸摸因為放上太多手指而被取消捂蕴,或者電話打斷