Swift4.0学习笔记(五)——按钮(UIButton)

1.创建按钮
  • UIButtonType.system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
  • UIButtonType.custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
  • UIButtonType.contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
  • UIButtonType.detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
  • UIButtonType.infoDark:为感叹号“!”圆形按钮
  • UIButtonType.infoLight:为感叹号“!”圆形按钮
    例如:
//定义控件x:30 y:100 width:80 height:40
let button = UIButton(type: .custom)//定义buttom为custom类型
button.frame = CGRect(x: 30, y: 100, width: 80, height: 40)
self.view.addSubview(button)
button.setTitle("custom", for: .normal)//设置按钮显示的文字

各种样式效果如下:
按钮样式效果
2.设置按钮不同状态下的文字、颜色和阴影颜色
  • UIControlState.normal//普通状态
  • UIControlState.highlighted//触摸状态
  • UIControlState.disabled//禁用状态
button.setTitle("普通状态", for: .normal)//设置按钮显示的文字
button.setTitle("触摸状态", for: .highlighted)
button.setTitle("禁用状态", for: .disabled)
button.setTitleColor(UIColor.red, for: UIControlState.normal)
button.setTitleColor(UIColor.blue, for: UIControlState.highlighted)
button.setTitleColor(UIColor.gray, for: UIControlState.disabled)
button.setTitleShadowColor(UIColor.green, for:.normal) //普通状态下文字阴影的颜色
button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通状态下文字阴影的颜色
button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通状态下文字阴影的颜色
3.按钮背景颜色设置
  • button.backgroundColor
button.backgroundColor = UIColor.green
4.按钮字体和大小设置
  • button.titleLabel?.font
let button = UIButton(type: .system)//定义buttom为custom类型
button.frame = CGRect(x: 30, y: 70, width: 120, height: 40)
        self.view.addSubview(button)
button.setTitle("系统字体", for: .normal)//设置按钮显示的文字
button.titleLabel?.font = UIFont.systemFont(ofSize: 23)
button.setTitleColor(UIColor.red, for: UIControlState.normal)

        
let button1 = UIButton(type: .system)//定义buttom为custom类型
button1.frame = CGRect(x: 30, y: 120, width: 120, height: 40)
        self.view.addSubview(button1)
button1.setTitle("其它字体", for: .normal)//设置按钮显示的文字
button1.titleLabel?.font = UIFont.systemFont(ofSize: 23)
button1.setTitleColor(UIColor.red, for: UIControlState.normal)
button1.titleLabel?.font = UIFont.init(name: "HelveticaNeue-Bold", size: 23)//使用其它字体
字体效果.png
5.设置按钮图标
  • button.setImage(UIImage?, for: UIControlState)
    当按钮类型为custom,处于highlighted和disable状态下图标会变暗,我们可以通过设置来禁用这种情况
button.setImage(UIImage(named:"alarm"), for: .normal)
button.adjustsImageWhenHighlighted = false //使触摸模式下按钮也不会变暗
button.adjustsImageWhenDisabled = false //使禁用模式下按钮也不会变暗
带图标的按钮.png

从上面的运行效果图可以看出,图标和文字几乎是贴在一起的,或者说图标能不能放在相对于文字的其它位置,我们一一来尝试一下。

调整文字和图标之间的间距
  • 通过图片偏移量(imageEdgeInsets)设置间距
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)
imageEdgeInsets.png
  • 通过文字偏移量(titleEdgeInsets)设置间距
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
titleEdgeInsets.png
改变图标与文字的相对位置

如果我们想要把文字和图片位置调换下(即文字在前、图片在后),或者文字和图片改成上下排列,那么同样通过设置 titleEdgeInsets 和 imageEdgeInsets 即可实现。

let imageSize = button.imageRect(forContentRect: button.frame)//获取图标的CGRect
let titleFont = button.titleLabel?.font//获取字体
let titleSize = button.currentTitle!.size(withAttributes:[NSAttributedStringKey.font: titleFont!])//获取文字的尺寸
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2) , bottom: 0, right: 0)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -(titleSize.width * 2 + 10))

效果如下:
图文换位.png

为方便快速的设置图片和文字的相对位置,以及间距,我们可以对UIButton进行扩展。
新建一个swift文件ButtonExt.swift

import UIKit
extension UIButton{
    func set(icon image: UIImage?, title: String, titleLocation: UIViewContentMode, padding: CGFloat, state: UIControlState ) {
        self.imageView?.contentMode = .center
        self.setImage(image, for: state)
        relativeLocation(title: title, location: titleLocation, padding: padding)
        self.titleLabel?.contentMode = .center
        self.setTitle(title, for: state)
    }
    
    private func relativeLocation(title: String, location: UIViewContentMode, padding: CGFloat){
        let imageSize = self.imageRect(forContentRect: self.frame)
        let titleFont = self.titleLabel?.font!
        let titleSize = title.size(withAttributes: [NSAttributedStringKey.font : titleFont!])
        
        var titleInsets: UIEdgeInsets
        var imageInsets: UIEdgeInsets
        
        switch location {
        case .top:
            titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + padding),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
        case .left:
            titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -(titleSize.width * 2 + padding))
        case .bottom:
            titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + padding),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
        case .right:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -padding)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        default:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        self.titleEdgeInsets = titleInsets
        self.imageEdgeInsets = imageInsets
    }
}

使用说明

let button1 = UIButton(type: .custom)//定义buttom为custom类型
button1.frame = CGRect(x: 30, y: 120, width: 120, height: 40)
        self.view.addSubview(button1)
button1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button1.setTitleColor(UIColor.red, for: UIControlState.normal)
button1.set(icon: UIImage(named:"alarm"), title: "闹钟", titleLocation: .top, padding: 10, state: .normal)

效果截图:
字上图下.png
6.设置按钮背景图片
  • button.setBackgroundImage(UIImage?, for: UIControlState)
button.setBackgroundImage(UIImage(named:"bgImg"), for: .normal)
背景图片.png
7.按钮文字太长处理方式

默认情况下,如果按钮文字太长超过按钮尺寸,则会省略中间的文字
文字处理.png

我们可以通过修改按钮中 titleLabel 的 lineBreakMode 属性,便可以调整按钮在文字超长的情况下如何显示,以及是否换行。

button.titleLabel?.lineBreakMode

lineBreakMode 共支持如下几种样式:

  • byTruncatingHead:省略头部文字,省略部分用...代替
  • byTruncatingMiddle:省略中间部分文字,省略部分用...代替(默认)
  • byTruncatingTail:省略尾部文字,省略部分用...代替
  • byClipping:直接将多余的部分截断
  • byWordWrapping:自动换行(按词拆分)
  • byCharWrapping:自动换行(按字符拆分)

注意:当设置自动换行后(byWordWrapping 或 byCharWrapping),我们可以在设置 title 时通过 \n 进行手动换行。

8.按钮的点击事件

常用的触摸事件类型:

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

我们通常通过addTarget为按钮添加点击事件

button.addTarget(Any?, action: Selector, for: UIControlEvents)
  • 不传递点击对象
 override func viewDidLoad() {
        super.viewDidLoad()
//        self.view.backgroundColor = UIColor.lightText
        //定义控件x:30 y:100 width:80 height:40
       let button = UIButton(type: .custom)//定义buttom为custom类型
        button.frame = CGRect(x: 30, y: 70, width: 120, height: 40)
        self.view.addSubview(button)
        button.setTitle("按钮", for: .normal)//设置按钮显示的文字
        button.titleLabel?.font = UIFont.systemFont(ofSize: 23)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"bgImg"), for: .normal)
        button.addTarget(self, action: #selector(click), for: .touchUpInside)
    }
    
    
    @objc func click(){
        print("没有传递触摸对象")
    }
不传递点击对象.png
  • 传递点击对象
button.addTarget(self, action: #selector(click(_:)), for: .touchUpInside)

@objc func click(_ sender: UIButton){
       print("传递触摸对象")
}
传递触摸对象.png
  • 传递参数给相关的方法
    有时候我们需要将一些参数传到方法里面,但是selector里面的方法如果有参数,参数只能是点击对象,那怎么办呢?我们可以通过给button设置tag的方式将参数传递到方法里面
[图片上传中...(设置tag.png-4399e1-1514365204496-0)]
button.addTarget(self, action: #selector(click(_:)), for: .touchUpInside)
button.tag = 1

  
@objc func click(_ sender: UIButton){
       let tag = sender.tag
       print("传递的tag:\(tag)")
        
}
设置tag.png

按钮是app里面使用场景非常多的控件,我的笔记里面只讲述最基本的一些用法,更高级的一些用法就需要你们去尝试了,最后关于参数的传递问题,我还没有理解数据绑定的方式,设置tag只能满足一些基本的使用场景,更多复杂的场景这种方式就显得非常局限了,等我理解了数据绑定之后再来补全最后这部分吧!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,158评论 0 17
  • 一、简介 <<UIButton(按钮) : 既能显示文字,又能显示图片,还能随时调整内部图片和文字的位置,实现了监...
    无邪8阅读 5,550评论 0 2
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 46,319评论 22 663
  • //UIButton和UIImageView常用属性和常用方法总结 //MARK: - UIButton常用属性和...
    专注_刻意练习阅读 690评论 0 0
  • 也许很多人像我一样,有一个背包梦,背上行囊去旅行。 也许很多人更喜欢去旅游。 旅行和旅游,又有什么不一样的意义。 ...
    预书阅读 358评论 2 1