Swift4.0學(xué)習(xí)筆記(五)——按鈕(UIButton)

1.創(chuàng)建按鈕
  • UIButtonType.system:前面不帶圖標(biāo),默認(rèn)文字顏色為藍(lán)色捍壤,有觸摸時(shí)的高亮效果
  • UIButtonType.custom:定制按鈕兔魂,前面不帶圖標(biāo),默認(rèn)文字顏色為白色愕提,無(wú)觸摸時(shí)的高亮效果
  • UIButtonType.contactAdd:前面帶“+”圖標(biāo)按鈕,默認(rèn)文字顏色為藍(lán)色潮孽,有觸摸時(shí)的高亮效果
  • UIButtonType.detailDisclosure:前面帶“!”圖標(biāo)按鈕揪荣,默認(rèn)文字顏色為藍(lán)色,有觸摸時(shí)的高亮效果
  • UIButtonType.infoDark:為感嘆號(hào)“!”圓形按鈕
  • UIButtonType.infoLight:為感嘆號(hào)“!”圓形按鈕
    例如:
//定義控件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)//設(shè)置按鈕顯示的文字

各種樣式效果如下:
按鈕樣式效果
2.設(shè)置按鈕不同狀態(tài)下的文字往史、顏色和陰影顏色
  • UIControlState.normal//普通狀態(tài)
  • UIControlState.highlighted//觸摸狀態(tài)
  • UIControlState.disabled//禁用狀態(tài)
button.setTitle("普通狀態(tài)", for: .normal)//設(shè)置按鈕顯示的文字
button.setTitle("觸摸狀態(tài)", for: .highlighted)
button.setTitle("禁用狀態(tài)", 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) //普通狀態(tài)下文字陰影的顏色
button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通狀態(tài)下文字陰影的顏色
button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通狀態(tài)下文字陰影的顏色
3.按鈕背景顏色設(shè)置
  • button.backgroundColor
button.backgroundColor = UIColor.green
4.按鈕字體和大小設(shè)置
  • 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("系統(tǒng)字體", for: .normal)//設(shè)置按鈕顯示的文字
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)//設(shè)置按鈕顯示的文字
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.設(shè)置按鈕圖標(biāo)
  • button.setImage(UIImage?, for: UIControlState)
    當(dāng)按鈕類型為custom仗颈,處于highlighted和disable狀態(tài)下圖標(biāo)會(huì)變暗,我們可以通過(guò)設(shè)置來(lái)禁用這種情況
button.setImage(UIImage(named:"alarm"), for: .normal)
button.adjustsImageWhenHighlighted = false //使觸摸模式下按鈕也不會(huì)變暗
button.adjustsImageWhenDisabled = false //使禁用模式下按鈕也不會(huì)變暗
帶圖標(biāo)的按鈕.png

從上面的運(yùn)行效果圖可以看出椎例,圖標(biāo)和文字幾乎是貼在一起的挨决,或者說(shuō)圖標(biāo)能不能放在相對(duì)于文字的其它位置,我們一一來(lái)嘗試一下订歪。

調(diào)整文字和圖標(biāo)之間的間距
  • 通過(guò)圖片偏移量(imageEdgeInsets)設(shè)置間距
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)
imageEdgeInsets.png
  • 通過(guò)文字偏移量(titleEdgeInsets)設(shè)置間距
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
titleEdgeInsets.png
改變圖標(biāo)與文字的相對(duì)位置

如果我們想要把文字和圖片位置調(diào)換下(即文字在前脖祈、圖片在后),或者文字和圖片改成上下排列刷晋,那么同樣通過(guò)設(shè)置 titleEdgeInsets 和 imageEdgeInsets 即可實(shí)現(xiàn)盖高。

let imageSize = button.imageRect(forContentRect: button.frame)//獲取圖標(biāo)的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

為方便快速的設(shè)置圖片和文字的相對(duì)位置慎陵,以及間距,我們可以對(duì)UIButton進(jìn)行擴(kuò)展喻奥。
新建一個(gè)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
    }
}

使用說(shuō)明

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.設(shè)置按鈕背景圖片
  • button.setBackgroundImage(UIImage?, for: UIControlState)
button.setBackgroundImage(UIImage(named:"bgImg"), for: .normal)
背景圖片.png
7.按鈕文字太長(zhǎng)處理方式

默認(rèn)情況下席纽,如果按鈕文字太長(zhǎng)超過(guò)按鈕尺寸,則會(huì)省略中間的文字
文字處理.png

我們可以通過(guò)修改按鈕中 titleLabel 的 lineBreakMode 屬性撞蚕,便可以調(diào)整按鈕在文字超長(zhǎng)的情況下如何顯示润梯,以及是否換行。

button.titleLabel?.lineBreakMode

lineBreakMode 共支持如下幾種樣式:

  • byTruncatingHead:省略頭部文字甥厦,省略部分用...代替
  • byTruncatingMiddle:省略中間部分文字纺铭,省略部分用...代替(默認(rèn))
  • byTruncatingTail:省略尾部文字,省略部分用...代替
  • byClipping:直接將多余的部分截?cái)?/li>
  • byWordWrapping:自動(dòng)換行(按詞拆分)
  • byCharWrapping:自動(dòng)換行(按字符拆分)

注意:當(dāng)設(shè)置自動(dòng)換行后(byWordWrapping 或 byCharWrapping)刀疙,我們可以在設(shè)置 title 時(shí)通過(guò) \n 進(jìn)行手動(dòng)換行舶赔。

8.按鈕的點(diǎn)擊事件

常用的觸摸事件類型:

  • touchDown:?jiǎn)吸c(diǎn)觸摸按下事件,點(diǎn)觸屏幕
  • touchDownRepeat:多點(diǎn)觸摸按下事件庙洼,點(diǎn)觸計(jì)數(shù)大于1顿痪,按下第2镊辕、3或第4根手指的時(shí)候
  • touchDragInside:觸摸在控件內(nèi)拖動(dòng)時(shí)
  • touchDragOutside:觸摸在控件外拖動(dòng)時(shí)
  • touchDragEnter:觸摸從控件之外拖動(dòng)到內(nèi)部時(shí)
  • touchDragExit:觸摸從控件內(nèi)部拖動(dòng)到外部時(shí)
  • touchUpInside:在控件之內(nèi)觸摸并抬起事件
  • touchUpOutside:在控件之外觸摸抬起事件
  • touchCancel:觸摸取消事件油够,即一次觸摸因?yàn)榉派咸嗍种付蝗∠蛘唠娫挻驍?/li>

我們通常通過(guò)addTarget為按鈕添加點(diǎn)擊事件

button.addTarget(Any?, action: Selector, for: UIControlEvents)
  • 不傳遞點(diǎn)擊對(duì)象
 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)//設(shè)置按鈕顯示的文字
        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("沒(méi)有傳遞觸摸對(duì)象")
    }
不傳遞點(diǎn)擊對(duì)象.png
  • 傳遞點(diǎn)擊對(duì)象
button.addTarget(self, action: #selector(click(_:)), for: .touchUpInside)

@objc func click(_ sender: UIButton){
       print("傳遞觸摸對(duì)象")
}
傳遞觸摸對(duì)象.png
  • 傳遞參數(shù)給相關(guān)的方法
    有時(shí)候我們需要將一些參數(shù)傳到方法里面征懈,但是selector里面的方法如果有參數(shù)石咬,參數(shù)只能是點(diǎn)擊對(duì)象,那怎么辦呢卖哎?我們可以通過(guò)給button設(shè)置tag的方式將參數(shù)傳遞到方法里面
[圖片上傳中...(設(shè)置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)")
        
}
設(shè)置tag.png

按鈕是app里面使用場(chǎng)景非常多的控件鬼悠,我的筆記里面只講述最基本的一些用法,更高級(jí)的一些用法就需要你們?nèi)L試了亏娜,最后關(guān)于參數(shù)的傳遞問(wèn)題焕窝,我還沒(méi)有理解數(shù)據(jù)綁定的方式,設(shè)置tag只能滿足一些基本的使用場(chǎng)景维贺,更多復(fù)雜的場(chǎng)景這種方式就顯得非常局限了它掂,等我理解了數(shù)據(jù)綁定之后再來(lái)補(bǔ)全最后這部分吧!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末溯泣,一起剝皮案震驚了整個(gè)濱河市虐秋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌垃沦,老刑警劉巖客给,帶你破解...
    沈念sama閱讀 216,919評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異肢簿,居然都是意外死亡靶剑,警方通過(guò)查閱死者的電腦和手機(jī)蜻拨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)桩引,“玉大人官觅,你說(shuō)我怎么就攤上這事〔郏” “怎么了休涤?”我有些...
    開封第一講書人閱讀 163,316評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)笛辟。 經(jīng)常有香客問(wèn)我功氨,道長(zhǎng),這世上最難降的妖魔是什么手幢? 我笑而不...
    開封第一講書人閱讀 58,294評(píng)論 1 292
  • 正文 為了忘掉前任捷凄,我火速辦了婚禮,結(jié)果婚禮上围来,老公的妹妹穿的比我還像新娘跺涤。我一直安慰自己,他們只是感情好监透,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評(píng)論 6 390
  • 文/花漫 我一把揭開白布桶错。 她就那樣靜靜地躺著,像睡著了一般胀蛮。 火紅的嫁衣襯著肌膚如雪院刁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,245評(píng)論 1 299
  • 那天粪狼,我揣著相機(jī)與錄音退腥,去河邊找鬼。 笑死再榄,一個(gè)胖子當(dāng)著我的面吹牛狡刘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播困鸥,決...
    沈念sama閱讀 40,120評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼嗅蔬,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了窝革?” 一聲冷哼從身側(cè)響起购城,我...
    開封第一講書人閱讀 38,964評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎虐译,沒(méi)想到半個(gè)月后瘪板,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,376評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡漆诽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評(píng)論 2 333
  • 正文 我和宋清朗相戀三年侮攀,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了锣枝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,764評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡兰英,死狀恐怖撇叁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情畦贸,我是刑警寧澤陨闹,帶...
    沈念sama閱讀 35,460評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站薄坏,受9級(jí)特大地震影響趋厉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜胶坠,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評(píng)論 3 327
  • 文/蒙蒙 一君账、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧沈善,春花似錦乡数、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至澈侠,卻和暖如春劫侧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背哨啃。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留写妥,地道東北人拳球。 一個(gè)月前我還...
    沈念sama閱讀 47,819評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像珍特,于是被迫代替她去往敵國(guó)和親祝峻。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程扎筒,因...
    小菜c閱讀 6,402評(píng)論 0 17
  • 一莱找、簡(jiǎn)介 <<UIButton(按鈕) : 既能顯示文字,又能顯示圖片嗜桌,還能隨時(shí)調(diào)整內(nèi)部圖片和文字的位置奥溺,實(shí)現(xiàn)了監(jiān)...
    無(wú)邪8閱讀 5,650評(píng)論 0 2
  • 內(nèi)容抽屜菜單ListViewWebViewSwitchButton按鈕點(diǎn)贊按鈕進(jìn)度條TabLayout圖標(biāo)下拉刷新...
    皇小弟閱讀 46,756評(píng)論 22 665
  • //UIButton和UIImageView常用屬性和常用方法總結(jié) //MARK: - UIButton常用屬性和...
    專注_刻意練習(xí)閱讀 726評(píng)論 0 0
  • 也許很多人像我一樣,有一個(gè)背包夢(mèng)骨宠,背上行囊去旅行浮定。 也許很多人更喜歡去旅游相满。 旅行和旅游,又有什么不一樣的意義桦卒。 ...
    預(yù)書閱讀 368評(píng)論 2 1