0

我在 UIView 子类上使用 IB_DESIGNABLE 因为我希望能够以编程方式制作属性字符串,但让它出现在界面生成器中(让我不必运行应用程序来查看格式)

我被告知我可以将我的代码放入

- (void)prepareForInterfaceBuilder;

它在一定程度上起作用。它出现在界面生成器中。但是当我去运行APP时,格式丢失了。它仍然出现在界面生成器中,但不在应用程序中。

以下是我尝试用来创建我的属性字符串的方法,但它们没有出现在界面构建器中,也没有出现在应用程序运行时。

- (instancetype)initWithFrame:(CGRect)frame;
- (void)drawRect:(CGRect)frame;

但是,话虽如此,我找到了一种可以在 APP 中呈现但不在界面生成器中呈现的方法。

- (instancetype)initWithCoder:(NSCoder *)aDecoder;

话虽如此,解决方案是只使用两种方法。但是我想知道是否有另一种方法可以两全其美。

另外,我将添加一个代码片段来显示我在做什么,并为这个查询提供一些补充。

IB_DESIGNABLE
@interface FooLabel1 : UILabel
@property (nonatomic, copy) IBInspectable NSAttributedString *attributedText;
@end

@implementation FooLabel1

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self localizeattributedString];
    }
    return self;
}

- (void)localizeattributedString {
    NSMutableAttributedString *mat = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(
            @"Hello"
            @"Darkness my old friend"
         , nil) attributes:@{
        NSForegroundColorAttributeName : [UIColor orangeColor],
    }];
    [mat appendAttributedString:[[NSAttributedString alloc] initWithString:NSLocalizedString(@"world!", nil) attributes:@{
            NSFontAttributeName : [UIFont boldSystemFontOfSize:60],
            NSForegroundColorAttributeName : [UIColor blueColor]
    }]];
    self.attributedText = [mat autorelease];
}

- (void)prepareForInterfaceBuilder {
    [self localizeattributedString];
}

@end
4

1 回答 1

0

您问题中的解决方案可以正常工作,但原因不正确。您要做的是从和调用您的配置方法 ( localizeattributedString) ,如下所示。initWithCoder:initWithFrame:

prepareForInterfaceBuilder是一种特殊方法,在渲染IB_DESIGNABLE视图的上下文中调用。例如,如果自定义视图通常从 Web 服务获取其部分数据,prepareForInterfaceBuilder那么您只需提供示例数据即可。

@implementation FooLabel1

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self localizeattributedString];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self localizeattributedString];
    }
    return self;
}

- (void)localizeattributedString {
    ...
}

@end
于 2015-02-06T20:23:24.517 回答