UIButton不会变灰
UIButton在启用时不应该变成灰色/灰色= NO?
我在blackbackground上有一个简单的UIButton(没有自定义图像,没有自定义的东西,只是用IB拖动它,改变大小和标题)。
当我将它设置为禁用时,它仍然是白色的!
现在,我正在使用一个小的愚蠢的解决方法:隐藏blackbg 0,5 alpha的UIView在隐藏的button顶部= NO当我需要禁用button…但我想设置button正确…
有什么想法吗?
没有办法做一个UIButton“grayer”。 但是你可以使用这个技巧:
UIButton *myButton; myButton.alpha = 0.4; myButton.enabled = NO;
所以你的UIButton看起来不可用;)
还有另外一种方法,不需要按住整个button:
[startButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
然后,无论何时将启用的属性设置为NO,button的文本都会自动变灰。
我碰到这个问题,苹果发布了一个新的UIKit用户界面目录,用于在iOS 7中使用button。
在回答你的问题时, UIButton Class现在公开了一个名为adjustsImageWhenDisabled的属性,它是一个布尔值,用于确定当button被禁用时图像是否改变。
如果adjustsImageWhenDisabled属性设置为“YES”,则禁用button时图像变暗,默认值为YES。
只需像下面这样创build一个UIButton类别,并在要使用它的类中导入#import "UIButton+StateColors.h"
。
。H
#import <UIKit/UIKit.h> @interface UIButton (StateColors) -(void)makeDisabled:(BOOL)flag; @end
.M
#import "UIButton+StateColors.h" #define ENABLED_BUTTON_ALPHA 1 #define DISABLED_BUTTON_ALPHA 0.3 @implementation UIButton (StateColors) -(void)makeDisabled:(BOOL)flag { self.enabled = !flag; self.alpha = flag ? DISABLED_BUTTON_ALPHA : ENABLED_BUTTON_ALPHA; } @end
像这样使用它…
[self.emailBtn makeDisabled:NO]; [self.printBtn makeDisabled:YES];
这是一个通用的解决scheme,我希望…
我面临同样的问题,因为我设置了背景颜色。
我删除了背景颜色,并将其仅设置为UIControlStateNormal
,启用/禁用的默认行为开始出现。
如果你是设置背景颜色而不是图像尝试这个类别转换UIColor到UIImage:
从这里复制:
+ (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; }
然后使用这个:
[self.loginButton setBackgroundImage:[UIImage imageWithColor:greenColor] forState:UIControlStateNormal]; self.loginButton.enabled = NO;
将颜色设置为背景。 现在,当您启用/禁用,灰色的效果应该出现。