swift UIButton

本文介绍如何使用Swift创建UIButton,并展示了不同类型的按钮样式及其属性设置方法,包括文字大小、字体、换行等。

直接上代码看Swift语法下UIButton 的创建

[objc]  view plain copy
  1. let btn=UIButton.buttonWithType(UIButtonType.System) as! UIButton  
  2. btn.frame=CGRectMake(506020036)  
  3. btn.setTitle("I'm learn Swift", forState: UIControlState.Normal)  
  4. btn.backgroundColor=UIColor.lightGrayColor()  
  5. self.view .addSubview(btn)  


以上是简单的创建了button,我们还可以设置设置button的文字大小,字体

[objc]  view plain copy
  1. //设置字体  
  2. btn.titleLabel?.font=UIFont(name: "Zapfino", size30)  

还可以考虑文字换行设置

[objc]  view plain copy
  1. //设置换行  
  2. btn.setTitle("I'm learn Swift I'm learn Swift", forState: UIControlState.Normal)//将title加长,测试换行  
  3. btn.titleLabel?.numberOfLines=0//行数为0 意思根据文字自动换行  

属性

UIButton 有一个枚举

UIButtonType

专门用来指定button的类型

这里我们尝试一下接种类型看看效果、


[objc]  view plain copy
  1. //按钮的几种类型  
  2.   
  3. //系统默认button  
  4. let btn1=UIButton.buttonWithType(UIButtonType.System) as! UIButton  
  5. btn1.frame=CGRectMake(205032036);  
  6. btn1.setTitle("SystemButton", forState: UIControlState.Normal);  
  7. self.view.addSubview(btn1);  
  8.   
  9. //所有属性需要自定义,否则字体颜色为白色  
  10. let btn2=UIButton.buttonWithType(UIButtonType.Custom) as! UIButton  
  11. btn2.frame=CGRectMake(2010032036);  
  12. btn2.setTitle("CustomButton", forState: UIControlState.Normal);  
  13. btn2 .setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)  
  14. self.view.addSubview(btn2);  
  15.   
  16. //以下为几种带图标的button  
  17. let btn3=UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton  
  18. btn3.frame=CGRectMake(2015032036);  
  19. btn3.setTitle("DetailDisclosureButton", forState: UIControlState.Normal);  
  20. self.view.addSubview(btn3);  
  21.   
  22. let btn4=UIButton.buttonWithType(UIButtonType.InfoLight) as! UIButton  
  23. btn4.frame=CGRectMake(2020032036);  
  24. btn4.setTitle("InfoLightButton", forState: UIControlState.Normal);  
  25. self.view.addSubview(btn4);  
  26.   
  27. let btn5=UIButton.buttonWithType(UIButtonType.InfoDark) as! UIButton  
  28. btn5.frame=CGRectMake(2025032036);  
  29. btn5.setTitle("InfoDarkButton", forState: UIControlState.Normal);  
  30. self.view.addSubview(btn5);  
  31.   
  32. let btn6=UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton  
  33. btn6.frame=CGRectMake(2030032036);  
  34. btn6.setTitle("ContactAddButton", forState: UIControlState.Normal);  
  35. self.view.addSubview(btn6);  




需要注意的是 按照以上几种方式创建的button将不能相互转换为其他类型了





















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值