码迷,mamicode.com
首页 > 编程语言 > 详细

论 Swift 开发入门 : 按钮(UIButton)

时间:2015-03-18 10:38:04      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:swift   ios   按钮   uibutton   

转载请声明出处:http://blog.csdn.net/jinnchang/article/details/44403537

1、UIButton 概述

继承关系:UIButton -> UIControl -> UIView

控件样式:

技术分享

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(.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。参考资料如下:

论 Swift 开发入门 : 按钮(UIButton)

标签:swift   ios   按钮   uibutton   

原文地址:http://blog.csdn.net/jinnchang/article/details/44403537

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!