Swift - 按钮(UIButton)的用法
原文地址: http://hangge.com/blog/cache/detail_529.html 作者: yuhang1,按钮的创建
(1)按钮有下面四种类型:
UIButtonType.ContactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.DetailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.System:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.Custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
1
2
3
4
5
6
7
|
//创建一个ContactAdd类型的按钮
var
button:
UIButton
=
UIButton
.buttonWithType(
UIButtonType
.
ContactAdd
)
as
UIButton
;
//设置按钮位置和大小
button.frame=
CGRectMake
(10, 150, 100, 30);
//设置按钮文字
button.setTitle(
"按钮"
, forState:
UIControlState
.
Normal
)
self
.view.addSubview(button);
|
1
|
var
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:
UIControlEvents
.
TouchUpInside
)
func
tapped(){
println
(
"tapped"
)
}
//传递触摸对象(即点击的按钮),需要在定义action参数时,方法名称后面带上冒号
button.addTarget(
self
,action:
Selector
(
"tapped:"
),forControlEvents:
UIControlEvents
.
TouchUpInside
)
func
tapped(button:
UIButton
){
println
(button.titleForState(.
Normal
))
}
|