ios - 如何禁用自定义的 UIButton

标签 ios uibutton

我将 UIButton 子类化,并在 drawRect 方法中进行了一些自定义绘制,例如绘制 NSAttributedStringUIImage

但是,在我这样做之后,当 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/

相关文章:

iphone - Xcode 4.5.1 iOS5/5.1 IBAction 不工作。在 iOS6 中很好

ios - 如何为 UIButton 设置自定义渐变背景?

ios - IBInspectable setTitle :forState on UIButton not working

ios - iOS 中设置 CAGradient UIButton 的选中状态

ios - 如何在 Objective-C 中使用 buttonWithType 添加按钮样式?

iphone - TTPhotoViewController 数据重新加载

ios - 更改边界大小后 CALayer 的位置

ios - 如何将 CAGradientLayer 添加到 UIButton

ios - 如何检查 Regex 在 Objective-C 中是否有效?

ios - 具有 3 个表的 UINavigationController