swift4.0 UIButton小解

来源:互联网 发布:俄罗斯知乎 编辑:程序博客网 时间:2024/05/17 09:46
//  ViewController.swift//  ComponentsTest//  Created by 朱莹浩 on 2017/7/16.//  Copyright © 2017年 朱莹浩. All rights reserved.//import UIKitclass ViewController: UIViewController {        //定义一个UIButton按钮    let button:UIButton = UIButton(type: .system)        override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        buttonFounction()    }        //buttonFounction对button的一下属性进行设置    func buttonFounction() {                //button的大小位置        button.frame = CGRect(x: 30, y: 20, width: 100, height: 30)        //设置按钮显示的标题        button.setTitle("返回", for: .normal)        //设置按钮的背景颜色        button.backgroundColor = UIColor.orange        //设置点击响应事件        button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside)        print("it runing normally here!")        self.view.addSubview(button)    }        func tapped(_ button:UIButton) {        print("我摁下了这个按钮")    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}

1.UIButton的属性

如果从我们从元件选项中拖拽一个按钮到main.storyboard就会发现在按钮的属性框中有六种按钮可供选择
UIButtonType.system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
UIButtonType.contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.infoDark:为感叹号“!”圆形按钮
UIButtonType.infoLight:为感叹号“!”圆形按钮

2.UIButton的文字设置和颜色

在UIButton中有一个函数UIButton.setTitle(_ title String?, for state: UIControlState)用来设置UIButton的标题和文字在触摸下的状态
.normal为常规状态
.hightlighted为高亮
.disabled为禁用下的状态
按钮的字体设置为UIButton.titleLable?.font = UIFont.system(ofSize:)
另一个用来设置文字颜色的UIButton.setTitleColor(_ color:UIColor?, for state: UIControlState)

3.UIButton的点击响应

传递触摸对象的函数

UIButton.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside)

此时的函数体带参数 tapped(_ button:UIButton){}

不传递触摸对象的函数

button.addTarget(self, action:#selector(tapped), for:.touchUpInside)

此时的函数体带参数 tapped(){}

关于 controlEvents的参数如下:

touchDown:单点触摸按下事件,点触屏幕
touchDownRepeat:多点触摸按下事件,点触计数大于1,按下第2、3或第4根手指的时候
touchDragInside:触摸在控件内拖动时
touchDragOutside:触摸在控件外拖动时
touchDragEnter:触摸从控件之外拖动到内部时
touchDragExit:触摸从控件内部拖动到外部时
touchUpInside:在控件之内触摸并抬起事件
touchUpOutside:在控件之外触摸抬起事件
touchCancel:触摸取消事件,即一次触摸因为放上太多手指而被取消,或者电话打断

原创粉丝点击