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

转载请声明出处:

1、UIButton 概述继承关系:UIButton -> UIControl -> UIView2、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 = 2self.view.addSubview(commonButton)self.view.addSubview(customButton)}/// 响应按钮点击事件func buttonActions(sender: UIButton!) {println(sender.tag)}4、forState这个参数的作用是定义按钮的文字或图片在何种状态下才会显现。有以下几种状态:5、两种设置背景图片方式的区别setBackGroudImage:图片会被拉伸setImage:图片保持原大小

6、结语文章最后更新时间:2015年3月18日10:11:03。

Github 上项目地址:UIButtonSample

参考资料如下:

(1)

(2)UIKit User Interface Catalog: Buttons

,偶尔也要现实和虚伪一点,因为不那样做的话,很难混。

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

相关文章:

你感兴趣的文章:

标签云: