//设置全局变量,将下面的替换即可
//var myButton = UIButton();
//系统生成的viewDidLoad()方法
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//创建局部变量UIButton
let myButton = UIButton.init(type: .Custom);
//设置位置大小
myButton.frame = CGRectMake(100, 100, 200, 100);
//设置按钮标题
myButton.setTitle("按钮点击", forState: .Normal);
//设置标题字体大小
myButton.titleLabel?.font = UIFont.systemFontOfSize(32);
//设置按钮标题颜色
myButton.setTitleColor(UIColor.redColor(), forState: .Normal);
//设置按钮标题显示的位置
myButton.contentHorizontalAlignment = UIControlContentHorizontal.AlignmentLeft;
//设置背景图片
myButton.setBackgroundImage(UIImage.init(named: "paybg.png"), forState: .Normal);
//设置按钮背景颜色
//myButton.backgroundColor = UIColor.cyanColor();
//设置按钮标题高亮状态下的颜色
myButton.setTitleColor(UIColor.darkGrayColor(), forState: .Highlighted);
//设置按钮标题阴影位置,默认为(0,0)
myButton.titleLabel?.shadowOffset = CGSizeMake(2.0, 1.0);
//设置按钮标题阴影颜色
myButton.setTitleShadowColor(UIColor.blueColor(), forState: .Normal);
//设置按钮边框圆角
myButton.layer.cornerRadius = 10;
//设置按钮边框宽度,默认为0
myButton.layer.borderWidth = 2;
//设置按钮边框颜色,默认为黑色
myButton.layer.borderColor = UIColor.brownColor().CGColor;
//设置圆角之外的界面是否剪切,swift中的YES和NO改成了true和false
myButton.clipsToBounds = true;
//设置按钮tag值
myButton.tag = 2;
//设置按钮点击事件,Swift语言中当你添加事件后,必须要添加,否则会crash
/*
//此处要注意:
2.2版本之前,这样写不会出现警告,也不会出现错误
myButton.addTarget(self, action:"buttonClick", forControlEvents: .TouchUpInside);
现在2.2版本,如果这样写会出现警告,点出警告,系统会帮你修订正确方法:
myButton.addTarget(self, action:#selector(ViewController.buttonClick(_:)), forControlEvents: .TouchUpInside); */
//也可以这样写
myButton.addTarget(self, action:#selector(buttonClick), forControlEvents: .TouchUpInside);
//添加视图
self.view.addSubview(myButton);
}
//按钮的点击事件
func buttonClick(sender:UIButton!){
print("print输出按钮的tag值",sender.tag);
NSLog("NSLog输出按钮的tag值.....%d", sender.tag);
}