一绪妹、內容概要
按鈕是所有UI體系中非常重要的組件宫静,在iOS中按鈕UIButton的使用也非常靈活走净,本文將從以下幾點介紹UIButton的使用(基于Swift2.0):1.UIButton基礎
2.UIButton圖片使用
3.圓角按鈕
4.復選框按鈕
5.倒計時按鈕(閃爍問題也輕松解決)
6.貪婪按鈕(父控件事件也歸我,擴大事件響應區(qū)域)
二孤里、UIButton基礎
2.1創(chuàng)建
UIButton提供了一個簡單的構造方法
convenience init(type buttonType: UIButtonType)
此方法中需要我們傳入一個UIButtonType枚舉類型伏伯,使用代碼如下:
enum UIButtonType : Int {
case Custom // 自定義風格
case System // 圓角矩形
case DetailDisclosure // 藍色小箭頭
case InfoLight // 亮色感嘆號
case InfoDark // 暗色感嘆號
case ContactAdd // 十字加號
}
func createButton() {
let button = UIButton(type: UIButtonType.System)
button.frame = CGRectMake(50, 50, 100, 50)
button.setTitle("確定", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button)
}
func buttonPressed(button: UIButton) { }
Tips:
1.設置按鈕標題
func setTitle(_ title: String?, forState state: UIControlState)
此方式會在點擊時標題自動變?yōu)?strong>setTitle方法Normal狀態(tài)下的文字
不可通過
button.titleLabel?.text = "確定"
2.2圖片使用
UIButton提供了以下兩個接口使用圖片:
func setImage(image: UIImage?, forState state: UIControlState)
func setBackgroundImage(image: UIImage?, forState state: UIControlState)
(1)其中接口setImage用來設置按鈕的圖片,默認情況下捌袜,它會與按鈕文字水平線性排列
(2)接口setBackgroundImage用來設置按鈕的背景圖片说搅,setImage及按鈕文字都會顯示在背景圖片之上這里著重討論一下
setBackgroundImage接口,很多時候琢蛤,按鈕看起來是這樣的
這些按鈕蜓堕,背景相同,只是尺寸不一樣博其,下面來談一下套才,如何復用這一類圖片資源.
2.2.1代碼方式
2.2.1.1 原理說明
在UIImage接口中,有以下方法
func resizableImageWithCapInsets(_ capInsets: UIEdgeInsets) -> UIImage
使用此方法時慕淡,需要傳遞UIEdgeInsets作為參數背伴,創(chuàng)建接口如下:
func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets
這個方法提供了上下左右的參數來創(chuàng)建可變區(qū)域,如下圖(Tips:下圖標明的可變區(qū)域與視圖內邊距是不同的概念)
圖中,藍色標識為可變區(qū)域, 綠色標識為不變區(qū)域傻寂。UIEdgeInsets結構體的屬性top與bottom為一對息尺,用來指定縱向可變區(qū)域(黑色虛線矩形),left與right為一對疾掰,用來指定橫向可變區(qū)域(白色虛線矩形)搂誉。當UIButton/UIImageView的size大于UIImage的size時,會調整圖片中可變區(qū)域大小以鋪滿整個控件,具體調整規(guī)則如下:
(1)控件寬度大于圖片寬度静檬,拉伸白色虛線矩形
(2)控件高度大于圖片高度炭懊,拉伸黑色虛線矩形
(3)控件寬度小于圖片寬度時,橫向整體縮小(可變區(qū)與不變區(qū)比例不變)
(4)控件高度小于圖片高度時拂檩,縱向整體縮小(可變區(qū)與不變區(qū)比例不變)
iOS系統(tǒng)會根據設備的分辨率自動加載1倍圖侮腹、2倍圖、3倍圖稻励,而方法resizableImageWithCapInsets中的上下左右是以像素為單位父阻,這就要求在使用時,根據x倍圖望抽,來設置對應的邊距加矛,例如:
let image = UIImage(named: "image_name")
//1倍圖時上下左右邊距都是25
let padding = 25 * (image?.scale)!
let edge = UIEdgeInsetsMake(padding, padding, padding, padding)
let resizeImage = image?.resizableImageWithCapInsets(edge)button.setBackgroundImage(resizeImage!, forState: UIControlState.Normal)
2.2.1.2性能與可變區(qū)域大小的關系
(1)性能最好:可變區(qū)為1像素寬或者高時,繪圖時通過拉伸1像素方式
(2)性能較好:可變區(qū)為整張圖片糠聪,方法**resizableImageWithCapInsets**參數為**UIEdgeInsetsZero**荒椭,繪制時通過平鋪整張圖片方式
(3)性能較差:可變區(qū)寬或者高大于1像素時谐鼎,繪圖時通過平鋪方式舰蟆,此種方式性能較差,但是在實際開發(fā)中此種方式也是用的最多的一種狸棍。
Tips
在一些應用中身害,應用程序有一些非純色背景,這個背景會在多個界面使用草戈,由于設備分辨率塌鸯、界面控件的尺寸差別,會要求制作多個尺寸的圖唐片,導致ipa包變大丙猬、內存使用增加。這里結合上面(2)設置可變區(qū)為整張圖片费韭,可以解決此問題,原理請看無縫貼圖
示例代碼如下:
let image = UIImage(named: "tile")
let resizeImage = image?.resizableImageWithCapInsets(UIEdgeInsetsZero)
self.bkImageView.image = resizeImage
2.2.2 Asset Catalogs方式(推薦)
Xcode提供了Asset Catalogs的方式來管理圖片資源茧球,Asset Catalogs提供了可視化界面來設置圖片的可變區(qū),操作方便星持,使用簡單抢埋。點擊右下方的Show Slicing
三個按鈕的作用
按鈕1只做水平拉伸
按鈕2水平垂直都拉伸
按鈕3只做垂直拉伸
水平及垂直的拉伸處理相同,這里以水平為例,選擇水平拉伸按鈕1后饥努,會提供三條操作線用來指定可變區(qū)及刪除區(qū)
可變區(qū):操作線1與操作線2指定的區(qū)域捡鱼,在拉伸時,會根據最終尺寸改變此區(qū)域的大小
刪除區(qū):操作線2與操作線3指定的區(qū)域(白色半透明層)酷愧,可以簡單的理解為堰汉,此區(qū)域在拉伸時會被直接刪除。使用方法跟普通圖片一樣伟墙,代碼如下:
let image = UIImage(named: "image_asset_name")
button.setBackgroundImage(image, forState: UIControlState.Normal)
三翘鸭、UIButton其它用法
3.1圓角按鈕
有些時候,我們需要一個圓形按鈕戳葵,例如頭像:
let image = UIImage(named: "user_avatar")
self.button.setImage(image, forState: UIControlState.Normal)
self.button.imageView?.layer.cornerRadius = self.button.frame.width / 2
func checkBoxButton() {
let frame = CGRectMake(68, 79, 300, 128)
let button = UIButton(type: UIButtonType.Custom)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.frame = frame
button.titleLabel?.font = UIFont.systemFontOfSize(30)
utton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
button.setTitle("復選框按鈕", forState: UIControlState.Normal)
//上面是樣式的設定,下面才是跟復選框有關
button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
button.setImage(UIImage(named: "check"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "uncheck"), forState: UIControlState.Selected)
self.view.addSubview(button)
}
func buttonPressed(button: UIButton) {
button.selected = !button.selected
}
3.3倒計時按鈕(閃爍問題也輕松解決)
很多應用中發(fā)短信倒計時功能拱烁,一般都會將NSTimer與UIButton結合來實現此功能生蚁,如果UIButton是這么初使化的:
let button = UIButton(type: UIButtonType.System)
在測試時會發(fā)現,當定時器每隔一秒更改標題時戏自,會有閃爍現象邦投,將UIButtonType.System更改為UIButtonType.Custom即可
這里提供封裝好的倒計時按鈕大家可以直接下載使用http://00red.com/download/Swift之貪婪的UIButton/ILCountDownButton.swift使用示例如下:
let frame = CGRectMake(50, 50, 100, 40)
let countButton = ILCountDownButton(count: 5)
countButton.frame = frame
countButton.setBackgroundImageForCount(UIImage(named: "bk_count")!)
countButton.setBackgroundImageForRestart(UIImage(named: "bk_restart")!)
countButton.setTitleForRestart("重新發(fā)送")
self.view.addSubview(countButton)
四、貪婪按鈕
UIButton的frame會直接影響到setImage及setBackgroundImage的顯示效果擅笔,有的時候我們只需要擴大UIButton的點擊區(qū)域志衣,而不想直接修改UIButton的frame而影響顯示。這時可以通過以下方法來處理
將UIButton的父視圖(superView)的點擊事件占有猛们,所有的觸控操作全部轉嫁到UIButton控件上念脯。
iOS在處理事件分發(fā)時,分為兩個步驟:
第一步弯淘,查找哪一個UI組件響應此事件
第二步绿店,事件處理,響應者鏈庐橙。
要實現事件的轉嫁假勿,在第一步中來處理即可,代碼如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createButton()
}
func leftItemClick() {
print("掃一掃")
}
func createButton() {
let button = ILGreedButton(type: UIButtonType.Custom)
button.frame = CGRectMake(50, 150, 100, 50)
button.setTitle("確定", forState: UIControlState.Normal)
button.backgroundColor = UIColor.redColor()
button.addTarget(self, action: #selector(ViewController.buttonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
// button.titleLabel?.text = "queding" 這種方式不顯示文字
self.view.addSubview(button)
}
func buttonPressed(button: UIButton) {
print("heheh")
}
}
class ILGreedButton: UIButton {
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
return self
}
}
在使用ILGreedButton時态鳖,就會出現點擊父視圖转培,UIButton響應事件的效果(只是出現在以UIButton為中心的一定范圍內點擊才有效)