我正在尝试以下代码使UIButton看起来已禁用:
btnYourButton.alpha = 0.6f;
btnYourButton.enabled = NO;
启用制作时(当然也要看起来启用)
btnYourButton.alpha = 1.0f;
btnYourButton.enabled = YES;
难道没有任何方法可以让我在一条语句中同时执行这两项操作(使UIButton禁用/启用,并使其看起来禁用/启用)吗?
或者您可以尝试对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
我知道这是一个非常古老的问题,但这里有一个非常好的解决方案。只需创建一个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];
另一个选项是更改禁用状态的文本颜色(例如为浅灰色)。在情节提要编辑器中,从"状态配置"弹出按钮中选择"禁用",然后使用"文本颜色"弹出按钮更改文本颜色。在代码中,使用-setTitleColor:forState:消息。
(我意识到这是一篇较旧的帖子,但我认为其他人可能会喜欢这个选项)