1

好吧,我以为我有一个好主意。带有帽插图的 UIButton 自动应用于背景图像。

@implementation JLTCapInsetButton

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
{
    CGFloat leftRight = (image.size.width - 1) / 2;
    CGFloat topBottom = (image.size.height - 1) / 2;
    UIEdgeInsets insets = UIEdgeInsetsMake(topBottom, leftRight, topBottom, leftRight);
    UIImage *capInsetImage = [image resizableImageWithCapInsets:insets];

    [super setBackgroundImage:capInsetImage forState:state];
}

@end

这不起作用,因为 IB 不使用-setBackgroundImage:forState:. 我对此的解决方法是使用-awakeFromNib.

- (void)awakeFromNib
{
    [self JLT_fixBackgroundImageForState:UIControlStateNormal];
    [self JLT_fixBackgroundImageForState:UIControlStateHighlighted];
    [self JLT_fixBackgroundImageForState:UIControlStateDisabled];
    [self JLT_fixBackgroundImageForState:UIControlStateSelected];
    [self JLT_fixBackgroundImageForState:UIControlStateSelected | UIControlStateHighlighted];
    [self JLT_fixBackgroundImageForState:UIControlStateSelected | UIControlStateDisabled];
}

- (void)JLT_fixBackgroundImageForState:(UIControlState)state
{
    UIImage *backgroundImage = [self backgroundImageForState:state];

    if (backgroundImage)
        [self setBackgroundImage:backgroundImage forState:state];
}

这不起作用,因为[self backgroundImageForState:state]如果图像被设置为总是返回一个值UIControlStateNormal

解码时是否有一种干净的方法来挂钩背景图像的设置?有没有一种干净的方法来检测一个状态是否有背景图像,而不仅仅是来自基本状态的隐含图像?

4

1 回答 1

1

在修复之前保留对已应用于 UIControlStateNormal 的图像的引用如何?对于后续的控制状态,只需在应用修复之前检查图像是否相同,如果是,请跳过修复该状态的图像...

于 2013-04-12T16:40:26.887 回答