(1)按鈕有下面四種類型:
1
2
3
4
5
6
7
|
//創建一個ContactAdd類型的按鈕 let button: UIButton = UIButton (type:. ContactAdd ) //設置按鈕位置和大小 button.frame= CGRectMake (10,
150, 100, 30) //設置按鈕文字 button.setTitle( "按鈕" ,
forState: UIControlState . Normal ) self .view.addSubview(button); |
1
|
let button
= UIButton (frame: CGRectMake (10,
150, 100, 30)) |
1
2
3
|
button.setTitle( "普通狀態" ,
forState: UIControlState . Normal ) //普通狀態下的文字 button.setTitle( "觸摸狀態" ,
forState: UIControlState . Highlighted ) //觸摸狀態下的文字 button.setTitle( "禁用狀態" ,
forState: UIControlState . Disabled ) //禁用狀態下的文字 |
1
2
3
|
button.setTitleColor( UIColor .blackColor(),forState:
. Normal ) //普通狀態下文字的顏色 button.setTitleColor( UIColor .greenColor(),forState:
. Highlighted ) //觸摸狀態下文字的顏色 button.setTitleColor( UIColor .grayColor(),forState:
. Disabled ) //禁用狀態下文字的顏色 |
1
2
3
|
button.setTitleShadowColor( UIColor .greenColor(),forState:. Normal ) //普通狀態下文字陰影的顏色 button.setTitleShadowColor( UIColor .yellowColor(),forState:. Highlighted ) //普通狀態下文字陰影的顏色 button.setTitleShadowColor( UIColor .grayColor(),forState:. Disabled ) //普通狀態下文字陰影的顏色 |
1
|
button.backgroundColor= UIColor .blackColor() |
1
2
3
|
button.setImage( UIImage (named: "icon1" ),forState:. Normal ) //設置圖標 button.adjustsImageWhenHighlighted= false //使觸摸模式下按鈕也不會變暗 button.adjustsImageWhenDisabled= false //使禁用模式下按鈕也不會變暗 |
1
|
button.setBackgroundImage( UIImage (named: "background1" ),forState:. Normal ) |
1
2
3
4
5
6
7
8
9
10
11
|
//不傳遞觸摸對象(即點擊的按鈕) button.addTarget( self ,action: Selector ( "tapped" ),forControlEvents:. TouchUpInside ) func tapped(){ print ( "tapped" ) } //傳遞觸摸對象(即點擊的按鈕),需要在定義action參數時,方法名稱後面帶上冒號 button.addTarget( self ,action: Selector ( "tapped:" ),forControlEvents:. TouchUpInside ) func tapped(button: UIButton ){ print (button.titleForState(. Normal )) } |