1,按鈕的創建
(1)按鈕有下面四種類型:
1
2
3
4
5
6
7
|
//創建一個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) |
1
|
let button
= UIButton (frame: CGRect (x:10,
y:150, width:100, height:30)) |
2,按鈕的文字設置
1
2
3
|
button.setTitle( "普通狀態" , for :.normal) //普通狀態下的文字 button.setTitle( "觸摸狀態" , for :.highlighted) //觸摸狀態下的文字 button.setTitle( "禁用狀態" , for :.disabled) //禁用狀態下的文字 |
3,按鈕文字顏色的設置
1
2
3
|
button.setTitleColor( UIColor .black, for :
.normal) //普通狀態下文字的顏色 button.setTitleColor( UIColor .green, for :
.highlighted) //觸摸狀態下文字的顏色 button.setTitleColor( UIColor .gray, for :
.disabled) //禁用狀態下文字的顏色 |
4,按鈕文字陰影顏色的設置
1
2
3
|
button.setTitleShadowColor( UIColor .green, for :.normal) //普通狀態下文字陰影的顏色 button.setTitleShadowColor( UIColor .yellow, for :.highlighted) //普通狀態下文字陰影的顏色 button.setTitleShadowColor( UIColor .gray, for :.disabled) //普通狀態下文字陰影的顏色 |
5,按鈕文字的字體和大小設置
1
|
button.titleLabel?.font
= UIFont .systemFont(ofSize:
11) |
6,按鈕背景顏色設置
1
|
button.backgroundColor
= UIColor .black |
7,按鈕文字圖標的設置
1
2
3
|
button.setImage( UIImage (named: "icon1" ),forState:. Normal ) //設置圖標 button.adjustsImageWhenHighlighted= false //使觸摸模式下按鈕也不會變暗(半透明) button.adjustsImageWhenDisabled= false //使禁用模式下按鈕也不會變暗(半透明) |
1
2
3
4
|
let iconImage
= UIImage (named: "icon2" )?.withRenderingMode(.alwaysOriginal) button.setImage(iconImage, for :.normal) //設置圖標 button.adjustsImageWhenHighlighted
= false //使觸摸模式下按鈕也不會變暗(半透明) button.adjustsImageWhenDisabled
= false //使禁用模式下按鈕也不會變暗(半透明) |
默認圖片和文字的相對位置是固定的(按鈕在前,文字在後)。我們可以通過擴展UIButton來實現自由調整位置和偏移量,具體參考我寫的另一篇文章:Swift - 自由調整圖標按鈕中的圖標和文字位置(擴展UIButton)
8,設置按鈕背景圖片
1
|
button.setBackgroundImage( UIImage (named: "bg1" ), for :.normal) |
9,按鈕觸摸點擊事件響應
1
2
3
4
5
6
7
8
9
10
11
12
|
//不傳遞觸摸對象(即點擊的按鈕) 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)) } |
10,按鈕文字太長時的處理方法
默認情況下,如果按鈕文字太長超過按鈕尺寸,則會省略中間的文字。比如下面代碼:
1
2
3
4
5
|
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) |
1
2
|
//省略尾部文字 button.titleLabel?.lineBreakMode
= .byTruncatingTail |
- .byTruncatingHead:省略頭部文字,省略部分用...代替
- .byTruncatingMiddle:省略中間部分文字,省略部分用...代替(默認)
- .byTruncatingTail:省略尾部文字,省略部分用...代替
- .byClipping:直接將多餘的部分截斷
- .byWordWrapping:自動換行(按詞拆分)
- .byCharWrapping:自動換行(按字符拆分)
1
|
button.setTitle( "歡迎訪問\nhangge.com" , for :.normal) |
原文出自:www.hangge.com 轉載請保留原文鏈接:http://www.hangge.com/blog/cache/detail_529.html (沒我什麼事吧 我已經按要求保留原文鏈接了 0.0 )