您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 小技巧:為 UIButton 依狀態設定不同背景色

編輯:iOS 相關資訊

一、問題

在 Storyboard 的屬性面板直接設定按鈕的背景色,這個顏色在按下時不會改變。若需要「正常態一個色、按態另一個色」,該怎麼做?

二、方案一:準備兩張圖片

按鈕的 Image 屬性可以依狀態分別設定,所以最直觀的做法是準備兩張只有顏色不同的純色圖,然後在 Storyboard 中為不同 State 指定各自的圖。

缺點很明顯:維護成本高。將來換色系、或要做換膚功能時,每一套皮膚都得重新切一遍圖,/>

三、方案二:用程式動態生成純色圖(推薦)

按鈕的 BackgroundImage 同樣支援依狀態設定,那麼只要讓程式依傳入的顏色即時產生一張 1×1 的純色圖即可。為了方便重複使用,寫成 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);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    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];

四、順手寫一個十六進位轉色的巨集

#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]

這個巨集用位移取出 AARRGGBB 的各個通道。若你只需要 RGB 六位元寫法,可以固定 alpha 為 255。實務上把巨集改寫成 Category 方法(例如 + colorWithHex:)會更安全,因為巨集沒有型別檢查,也容易在運算式優先序上出錯。

五、幾個補充重點

1. 为什么用 BackgroundImage 而不是 backgroundColor? 因為 setBackgroundImage:forState: 是 UIKit 原生支援的狀態化 API,而 backgroundColor 沒有狀態變體。用一張 1×1 的純色圖當背景,實際渲染成本幾乎可忽略。

2. 用 UIGraphicsBeginImageContextWithOptions(size, NO, 0) 而非舊版的 UIGraphicsBeginImageContext,這樣在 Retina 螢幕上會自動產生 2x/3x 解析度的圖,邊緣才不會模糊。

3. 若你只是想要「按下時變暗」這種效果,其實不必換色,直接把 adjustsImageWhenHighlighted 設為 YES 即可;或用 iOS 15 起的 UIButton.Configuration,透過 configurationUpdateHandler 依 state 統一回傳不同樣式,這是目前最推薦的寫法:

button.configuration = UIButtonConfiguration.filledButtonConfiguration;
button.configurationUpdateHandler = ^(UIButton *btn) {
    UIButtonConfiguration *c = btn.configuration;
    c.baseBackgroundColor = btn.state & UIControlStateHighlighted
        ? [UIColor systemOrangeColor] : [UIColor systemBlueColor];
    btn.configuration = c;
};
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved