iOS小技巧 - 為按鈕設定不同狀態下的背景色

來源:互聯網
上載者:User

iOS小技巧 - 為按鈕設定不同狀態下的背景色
我們知道直接在Storyboard中設定按鈕的背景色是不能根據不同狀態來更改的,那問題來了,如果我們需要在不同的狀態下(比如按鈕沒有被按下或者被按下),使得按鈕呈現不同的背景色怎麼辦?   比如左邊是按鈕沒有被按下時的背景色,右邊是按鈕被按下時的背景色。 第一種方案我們知道按鈕的Image屬性可以在不同的狀態下設定不同的圖片,那最直觀的辦法就是提供兩種背景色的圖片,然後直接在Storyboard上通過設定不同狀態下Image屬性的值來達到目的。 但是這種方案最不好的地方就在於需要提供很多僅僅是顏色不同的圖片,如果以後背景色改成其他色系怎麼辦?設定以後提供換膚功能,每一種皮膚都要提供一整套這些背景色圖片嗎? 第二種方案我們還知道按鈕的BackgroundImage也是可以根據不同狀態來設定不同的背景圖片的,那方案就來了,讓程式根據顏色自動產生不同的純色背景圖片即可。 為了保證可複用性,定義一個UIButton的Category,實現如下: @implementation UIButton (FillColor) - (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {[self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];} + (UIImage *)imageWithColor:(UIColor *)color {CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);UIGraphicsBeginImageContext(rect.size);CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]);CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext(); return image;} @end上述代碼應該還是很直觀的,調用的辦法如下: [self.button setBackgroundColor:GetColorFromHex(0xffff9000) forState:UIControlStateNormal];[self.button setBackgroundColor:GetColorFromHex(0xffff6c00) forState:UIControlStateHighlighted];其中GetColorFromHex是我自己定義的一個宏: #define GetColorFromHex(hexColor) \[UIColor colorWithRed:((hexColor >> 16) & 0xFF) / 255.0 \green:((hexColor >>  8) & 0xFF) / 255.0 \blue:((hexColor >>  0) & 0xFF) / 255.0 \alpha:((hexColor >> 24) & 0xFF) / 255.0] 其實上述宏代碼寫成Category會更好,以後再做修改了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.