我在 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