創(chuàng)建
xib:直接拖
code:UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
注意:xib中直接拖進(jìn)去的button默認(rèn)為UIButtonTypeSystem,該類型默認(rèn)會(huì)對(duì)button做些一些定制化工作(包括字體,顏色等),如果我們?cè)谠擃愋偷幕A(chǔ)上對(duì)button做自定義背景圖片,會(huì)產(chǎn)生錯(cuò)誤的效果。對(duì)于我們最常用的按鈕,通常設(shè)定為UIButtonTypeCustom
背景圖片
設(shè)置常態(tài)下的背景圖片
[self.button setBackgroundImage:[UIImage imageNamed:@"green_btn_normal"] forState:UIControlStateNormal];
設(shè)置按下狀態(tài)的背景圖片
[self.button setBackgroundImage:[UIImage imageNamed:@"green_btn_selected"] forState:UIControlStateHighlighted];
注意:按下狀態(tài)時(shí),state的值是UIControlStateHighlighted,而不是selected,只有這樣設(shè)置,才能讓你的按鈕顯示出正確的顏色
實(shí)例解析
制作demo,需求如下:
創(chuàng)建2個(gè)按鈕
SystemTypeOriginal為storyboard中直接拖上去的button,type保持system不變,設(shè)置green_btn_normal.png為normal狀態(tài)的背景圖片,設(shè)置green_btn_selected.png為highlighted狀態(tài)的背景圖片
CustomTypeOriginal為storyboard中直接拖上去的button,type設(shè)置為Custom,設(shè)置green_btn_normal.png為normal狀態(tài)的背景圖片,設(shè)置green_btn_selected.png為highlighted狀態(tài)的背景圖片
運(yùn)行demo,效果圖如下:
Paste_Image.png
通過上圖分析可知:
SystemType下字體默認(rèn)為15,且字體顏色為藍(lán)色
CustomType下字體默認(rèn)為18,字體顏色為白色
普通狀態(tài)下的按鈕背景圖片與預(yù)期相符,green_btn_normal表示的是原始圖片的顏色,此時(shí)原始圖片顏色與按鈕背景顏色一致
此時(shí),按下SystemTypeOriginal,效果圖如下:
按下SystemTypeOriginal
上圖的按下效果變得非常詭異,與預(yù)期的green_btn_selected顏色相差甚遠(yuǎn),這就是上面說的,在systemtype下,設(shè)置背景圖片會(huì)產(chǎn)生錯(cuò)誤的效果,所以常用的按鈕都會(huì)設(shè)置為Customtype。
那么,我們按下CustomTypeOriginal,看下效果圖:
按下CustomTypeOriginal
現(xiàn)在按下的背景圖片就對(duì)了!
為什么要設(shè)置highlighted而不是selected
因?yàn)閎utton在按下時(shí),狀態(tài)是highlighted,而不是selected,所以設(shè)置selected是沒有作用的。