4

我有一个 UIImage 可以完美地调整大小,resizableImageWithCapInsets以制作包含文本标签的徽章。我很想知道有没有办法在故事板或用笔尖创建的视图中做到这一点?

没有技术上的理由要求这样做。大部分 UI 都是在笔尖中完成的,我希望尽可能多地保留在那里,而不是加载图像、使其可调整大小、查找文本尺寸、调整 UIImageView 的大小,然后在代码中应用标签。

我还不能让这个项目只支持 iOS6(部署目标 ios5+),所以不能选择使用布局约束。

4

1 回答 1

6

就在这里。

诀窍是覆盖-initWithCoder:和图像设置器(setImage:forState:setBackgroundImage:forState:)来创建您在 xib 中设置的相同图像的可调整大小版本。显然,它们仍然不会在 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
于 2012-09-27T05:18:23.707 回答