按钮可以用UIButton.buttonWithType创建,代码如下:
//创建一个contactadd类型的按钮
var button:UIButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton;
//设置按钮位置和大小
button.frame = CGRectMake(10, 150, 100, 30);
//设置按钮文字
button.setTitle("button", forState: UIControlState.Normal);
self.view.addSubview(button);
如果我们要创建一个custom定制类型的按钮,代码可以简化如下:
var button:UIButton = UIButton(frame: CGRectMake(10, 150, 100, 30));
//设置按钮文字,按钮有三种状态 :普通normal/触摸highlighted/禁用disabled
button.setTitle("button", forState: UIControlState.Normal);
由于costom默认按钮文字颜色是白色,在白的背景下无法看到,所以我们可以设置文字的颜色为黑色:
//普通状态下按钮文字颜色
button.setTitleColor(UIColor.blackColor(), forState: .Normal);
self.view.addSubview(button);
同样,我们也可以设置文字的阴影:
button.setTitleShadowColor(UIColor.blueColor(), forState: .Normal);
按钮的背景颜色:
button.backgroundColor = UIColor.redColor();
按钮的图片:
button.setImage(UIImage(named: "cloud223"), forState: .Normal);
或者:
//默认情况下,按钮在触摸下,按钮图片会变暗,不想变暗:
button.adjustsImageWhenHighlighted = false;
//设置在禁用状态下图标不变暗
button.adjustsImageWhenDisabled = false;
//设置按钮的背景图片
button.setBackgroundImage(UIImage(named:"cloud223"), forState: .Normal);
同理,我们也可以设置按钮的触摸事件:
button.addTarget(self, action:Selector("add"), forControlEvents: UIControlEvents.TouchUpInside);
func add(){
println("add");
}
如果我们要获取按钮对象:需要在定义的action参数时,方法名称后带上冒号:
button.addTarget(self, action:Selector("add:"), forControlEvents: UIControlEvents.TouchUpInside);
func add(butto:UIButton){
println(butto.titleColorForState(.Normal));
}
写的不好,不要见怪