swift中UIButton的使用

本文详细介绍如何使用 Swift 对 UIButton 进行完全定制,包括按钮的背景、图标、标题及响应事件等设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. let button = UIButton(type: UIButtonType.Custom)  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 添加到父视图,并设置frame  
  2. self.view.addSubview(button)  
  3. button.frame = CGRectMake(10.010.0200.040.0)  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 背景属性设置  
  2. button.backgroundColor = UIColor.yellowColor()  
  3. // button.setBackgroundImage(UIImage(named: "normalImage"), forState: UIControlState.Normal)  
  4. // button.setBackgroundImage(UIImage(named: "hightImage"), forState: UIControlState.Highlighted)  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 图标设置  
  2. button.setImage(UIImage(named: "normalImage"), forState: UIControlState.Normal)  
  3. button.setImage(UIImage(named: "hightImage"), forState: UIControlState.Highlighted)  
  4. button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -50.00.00.0)  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 标题设置  
  2. button.setTitle("button", forState: UIControlState.Normal)  
  3. button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)  
  4. button.setTitleColor(UIColor.redColor(), forState: UIControlState.Highlighted)  
  5. button.setTitleShadowColor(UIColor.greenColor(), forState: UIControlState.Normal)  
  6. button.titleLabel?.font = UIFont(name: "GillSans", size20.0)  
  7. button.titleEdgeInsets = UIEdgeInsetsMake(0.00.00.0, -50.0)  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. button.selected = false  
  2. button.enabled = true  
  3. button.userInteractionEnabled = true  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 响应事件  
  2. button.addTarget(self, action: Selector("buttonClick:"), forControlEvents: UIControlEvents.TouchUpInside)  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 响应事件  
  2. func buttonClick(button:UIButton) -> Void  
  3. {  
  4.         button.selected = !button.selected  
  5.         if button.selected == true  
  6.         {  
  7.             print("选中按钮")  
  8.               
  9.             let buttonTitle = button.titleLabel?.text  
  10.             print(buttonTitle)  
  11.         }  
  12.         else  
  13.         {  
  14.             print("未选中按钮")  
  15.         }  
  16. }  

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值