はいあります。
トリックは、 xib で設定した同じイメージのサイズ変更可能なバージョンを作成するために-initWithCoder:
、イメージ セッター (setImage:forState:
および) をオーバーライドすることです。setBackgroundImage:forState:
明らかに、xib 自体では適切にサイズ変更されませんが、初期化後に適切にサイズ変更されます。NAResizableButton
のカスタム クラスとして設定することを忘れないでくださいUIButton
。
確かに、プログラムでそれを行うよりも優れています。:)
インターフェース:
#import <UIKit/UIKit.h>
@interface NAResizableButton : UIButton
@end
実装:
#import "NAResizableButton.h"
@implementation NAResizableButton
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self setImage:[self imageForState:UIControlStateNormal] forState:UIControlStateNormal];
[self setImage:[self imageForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
[self setImage:[self imageForState:UIControlStateSelected] forState:UIControlStateSelected];
[self setImage:[self imageForState:UIControlStateDisabled] forState:UIControlStateDisabled];
[self setBackgroundImage:[self backgroundImageForState:UIControlStateNormal] forState:UIControlStateNormal];
[self setBackgroundImage:[self backgroundImageForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
[self setBackgroundImage:[self backgroundImageForState:UIControlStateSelected] forState:UIControlStateSelected];
[self setBackgroundImage:[self backgroundImageForState:UIControlStateDisabled] forState:UIControlStateDisabled];
}
return self;
}
- (void)setImage:(UIImage *)inImage forState:(UIControlState)inState
{
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2), ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2));
if ([inImage respondsToSelector:@selector(resizableImageWithCapInsets:)])
{
// iOS 5
inImage = [inImage resizableImageWithCapInsets:edgeInsets];
}
else
inImage = [inImage stretchableImageWithLeftCapWidth:edgeInsets.left topCapHeight:edgeInsets.top];
[super setImage:inImage forState:inState];
}
- (void)setBackgroundImage:(UIImage *)inImage forState:(UIControlState)inState
{
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2), ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2));
if ([inImage respondsToSelector:@selector(resizableImageWithCapInsets:)])
{
// iOS 5
inImage = [inImage resizableImageWithCapInsets:edgeInsets];
}
else
inImage = [inImage stretchableImageWithLeftCapWidth:edgeInsets.left topCapHeight:edgeInsets.top];
[super setBackgroundImage:inImage forState:inState];
}
@end