`
iaiai
  • 浏览: 2135990 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Swift开发入门:按钮(UIButton)

 
阅读更多
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(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
  • 大小: 22.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics