UIButton
属性设置如下:
///---创建button
func CreateButton()
{
///----实例化按钮对象
let button = UIButton.init(type:UIButtonType.System);
///--设置按钮的位置和大小
button.frame = CGRect(x:10,y:150,width:100,height:30);
///---设置按钮的文字
button.setTitle("点我试试",forState:.normal);
///---设置按钮的字体颜色
button.setTitleColor(UIColor.greenColor(),forState:.Highlighted);
button.setTitleShadowColor(UIColor.grayColor(),forState: .disabled);
///---设置字体阴影
button.setTitleShadowColor(UIColor.greenColor(),forState:.Highlighted);
button.setTitleShadowColor(UIColor.greenColor(),forState:.disabled);
///---设置按钮的背景色
button.backgroundColor = UIColor.whiteColor();
///---设置按钮被触摸的事件
button.addTarget(self,action: Selector("tapped"),forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(button);
}
func tapped()
{
print("触发了触摸事件");
}
说明:
按钮的样式的参数,如下:
UIButtonType.contanctAdd : "+"图标,默认文字为蓝色,有触摸时的高亮效果
UIButtonType.DEtaildiscloure : "!" 图标,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.System : 不带图标,,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.Custom : 定制按钮,不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
按钮的事件:
如果想在tapped 函数中获得按钮对象,需要定义action 的时候,方法名称后带上冒号。如:
button.addTarget(self,action: Selector("tapped:"),forControlEvents: UIControlEvents.TouchUpInside); 然后在方法中可以获得按钮对象了:
func tapped(button : UIButton)
{
print(button.titleState(.normal));
}
运行结果: