直接上代码看Swift语法下UIButton 的创建
- let btn=UIButton.buttonWithType(UIButtonType.System) as! UIButton
- btn.frame=CGRectMake(50, 60, 200, 36)
- btn.setTitle("I'm learn Swift", forState: UIControlState.Normal)
- btn.backgroundColor=UIColor.lightGrayColor()
- self.view .addSubview(btn)
以上是简单的创建了button,我们还可以设置设置button的文字大小,字体
- //设置字体
- btn.titleLabel?.font=UIFont(name: "Zapfino", size: 30)
还可以考虑文字换行设置
- //设置换行
- btn.setTitle("I'm learn Swift I'm learn Swift", forState: UIControlState.Normal)//将title加长,测试换行
- btn.titleLabel?.numberOfLines=0//行数为0 意思根据文字自动换行
属性
UIButton 有一个枚举
UIButtonType
专门用来指定button的类型
这里我们尝试一下接种类型看看效果、
- //按钮的几种类型
- //系统默认button
- let btn1=UIButton.buttonWithType(UIButtonType.System) as! UIButton
- btn1.frame=CGRectMake(20, 50, 320, 36);
- btn1.setTitle("SystemButton", forState: UIControlState.Normal);
- self.view.addSubview(btn1);
- //所有属性需要自定义,否则字体颜色为白色
- let btn2=UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
- btn2.frame=CGRectMake(20, 100, 320, 36);
- btn2.setTitle("CustomButton", forState: UIControlState.Normal);
- btn2 .setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
- self.view.addSubview(btn2);
- //以下为几种带图标的button
- let btn3=UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton
- btn3.frame=CGRectMake(20, 150, 320, 36);
- btn3.setTitle("DetailDisclosureButton", forState: UIControlState.Normal);
- self.view.addSubview(btn3);
- let btn4=UIButton.buttonWithType(UIButtonType.InfoLight) as! UIButton
- btn4.frame=CGRectMake(20, 200, 320, 36);
- btn4.setTitle("InfoLightButton", forState: UIControlState.Normal);
- self.view.addSubview(btn4);
- let btn5=UIButton.buttonWithType(UIButtonType.InfoDark) as! UIButton
- btn5.frame=CGRectMake(20, 250, 320, 36);
- btn5.setTitle("InfoDarkButton", forState: UIControlState.Normal);
- self.view.addSubview(btn5);
- let btn6=UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton
- btn6.frame=CGRectMake(20, 300, 320, 36);
- btn6.setTitle("ContactAddButton", forState: UIControlState.Normal);
- self.view.addSubview(btn6);
需要注意的是 按照以上几种方式创建的button将不能相互转换为其他类型了