2012-02-08 50 views
3

我想下面的代碼,以使一個UIButton照看殘疾:任何其他選項使UIButton外觀禁用?

btnYourButton.alpha = 0.6f; 
btnYourButton.enabled = NO; 

當啓用使(當然把目光啓用)

btnYourButton.alpha = 1.0f; 
btnYourButton.enabled = YES; 

是不是有什麼辦法,由我可以在一個語句中執行這兩個操作(使UIButton禁用/啓用,並使其看起來禁用/啓用)?

回答

4

或者你可以嘗試繼承UIButton的,是這樣的:

文件MyKindOfButton.h

#import <UIKit/UIKit.h> 

@interface MyKindOfButton : UIButton 

@end 

文件MyKindOfButton.m

#import "MyKindOfButton.h" 

@implementation MyKindOfButton 

- (void)setEnabled:(BOOL)enabled { 

    [super setEnabled: enabled]; 

    if (enabled) { 
     self.alpha = 1.0f; 
    } else { 
     self.alpha = 0.6f; 

    } 
} 

@end 
0

另一種方法是更改​​文本顏色(以例如淺灰色)表示禁用狀態。在故事板編輯器中,從「狀態配置」彈出式按鈕中選擇「禁用」,然後使用「文本顏色」彈出式按鈕更改文本顏色。在代碼中,使用-setTitleColor:forState:消息。

(我知道這是一個老帖子,但我認爲其他人可能會喜歡這個選項)

1

我知道這是一個很古老的問題,但這裏是一個非常好的解決方案。只需創建一個UIColor類別並添加此方法。

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size 
{ 
    UIGraphicsBeginImageContext(size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetFillColorWithColor(context, color.CGColor); 
    CGContextFillRect(context, (CGRect){.size = size}); 

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return image; 
} 

+ (UIImage *)imageWithColor:(UIColor *)color 
{ 
    return [UIImage imageWithColor:color size:CGSizeMake(1, 1)]; 
} 

現在,您可以只設置和backgroundImage任何你想要的顏色,它會自動爲您處理禁用外觀。

[button setTitleColor:[UIColor someColor] forState:UIControlStateNormal]; 
相關問題