Swift开发入门:按钮(UIButton)

1、UIButton 概述
继承关系:UIButton -> UIControl -> UIView

控件样式:
[img]http://dl2.iteye.com/upload/attachment/0113/8635/49e16e2c-02f4-362b-babf-c1a0b111aa62.png[/img]

2、UIButton 初始化
(1)使用 buttonWithType 构建按钮,已有的六种类型如下:

enum UIButtonType : Int {
case Custom // 自定义风格
case System // 圆角矩形
case DetailDisclosure // 蓝色小箭头
case InfoLight // 亮色感叹号
case InfoDark // 暗色感叹号
case ContactAdd // 十字加号
}

(2)使用 frame 自定义按钮

3、使用示例

override func viewDidLoad() {

// 1、使用已有类型构建按钮
let commonButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
// 修改按钮位置及大小
commonButton.frame = CGRectMake(self.view.frame.width/2 - 100, 100, 200, 200)
// 设置按钮背景图片
commonButton.setBackgroundImage(UIImage(named:"logo.jpg"), forState: UIControlState.Normal)
// 添加点击事件
commonButton.addTarget(self, action: "buttonActions:", forControlEvents: UIControlEvents.TouchUpInside)
// 设置按钮标签
commonButton.tag = 1

// 2、自定义按钮
let customButton = UIButton(frame: CGRectMake(self.view.frame.width/2 - 100, 400, 200, 200))
// 设置按钮标题
customButton.setTitle("custom", forState: UIControlState.Normal)
// 设置按钮标题颜色
customButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
// 设置按钮标题阴影
customButton.setTitleShadowColor(UIColor.blackColor(), forState: UIControlState.Normal)
// 设置按钮阴影
customButton.titleLabel?.shadowOffset = CGSizeMake(1.0, 1.0)
// 设置按钮标题字体样式
customButton.titleLabel!.font = UIFont.systemFontOfSize(18)
// 设置按钮标题换行模式
customButton.titleLabel!.lineBreakMode = .ByTruncatingTail
// 设置按钮背景色
customButton.backgroundColor = UIColor(red:0.8,green:0.8,blue:0.8,alpha:1.0)
// 设置按钮内部内容边距
customButton.contentEdgeInsets = UIEdgeInsetsMake(-100, 0, 0, 0)
// 去掉高亮状态下的图像颜色加深
customButton.adjustsImageWhenHighlighted = false;
// 去掉禁用状态下的图像颜色加深
customButton.adjustsImageWhenDisabled = false;
// 添加按钮按下发光效果
customButton.showsTouchWhenHighlighted = true;
// 添加点击事件
customButton.addTarget(self,action:"buttonActions:",forControlEvents:UIControlEvents.TouchUpInside)
// 设置按钮标签
customButton.tag = 2

self.view.addSubview(commonButton)
self.view.addSubview(customButton)
}

/// 响应按钮点击事件
func buttonActions(sender: UIButton!) {
println(sender.tag)
}

4、forState
这个参数的作用是定义按钮的文字或图片在何种状态下才会显现。有以下几种状态:
Normal(正常状态)Highlighted(按下状态)Disabled(禁用状态)Selected(选中状态(手指已经离开))Application(应用程序标志)Reserved(预留状态)

5、两种设置背景图片方式的区别
setBackGroudImage:图片会被拉伸setImage:图片保持原大小

6、结语
Github 上项目地址:UIButtonSample 文章最后更新时间:2015年3月18日10:11:03。参考资料如下:
UIButton Class Reference
UIKit User Interface Catalog: Buttons
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值