我将 UIButton
子类化,并在 drawRect
方法中进行了一些自定义绘制,例如绘制 NSAttributedString
和 UIImage
。
但是,在我这样做之后,当 enabled
设置为 NO
时,自定义的 UIButton
不会变灰。我认为我的定制绘图发生在其状态之上。我该如何处理?
在这里分享我的绘图代码:
- (void)drawRect:(CGRect)rect
{
// Drawing code
if (self.faceUp) {
[self drawCardText:self.card.contents inRect:self.bounds];
} else {
[self drawCardImage:[UIImage imageNamed:CardBackImageName] inRect:self.bounds];
}
}
- (void)drawCardText:(NSString *)text inRect:(CGRect)rect
{
// set background color to white so text can be shown
[[UIColor whiteColor] setFill];
[[UIBezierPath bezierPathWithRect:rect] fill];
UIFont *preferedFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
UIFont *actualFont = [UIFont fontWithName:preferedFont.fontName
size:hypotf(rect.size.width, rect.size.height) / 6.0];
NSDictionary *attributes = @{NSFontAttributeName: actualFont};
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
[self setAttributedTitle:attributedText forState:UIControlStateNormal];
}
- (void)drawCardImage:(UIImage *)image inRect:(CGRect)rect
{
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 1.0f);
[image drawInRect:rect];
UIImage *actualImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[[UIColor colorWithPatternImage:actualImage] setFill];
[[UIBezierPath bezierPathWithRect:rect] fill];
}
最佳答案
您可能需要自己添加一个带有灰色和一些 alpha 的叠加 View 。再次启用按钮时移除叠加层。
关于ios - 如何禁用自定义的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22343312/