好吧,我以为我有一个好主意。带有帽插图的 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
。
解码时是否有一种干净的方法来挂钩背景图像的设置?有没有一种干净的方法来检测一个状态是否有背景图像,而不仅仅是来自基本状态的隐含图像?