Objective c IB_可使用属性字符串进行设计
我在UIView子类上使用IB_DESIGNABLE,因为我希望能够以编程方式生成属性字符串,但让它出现在Interface builder中,这样我就不用运行应用程序来查看格式了 有人告诉我,我可以把我的代码放入Objective c IB_可使用属性字符串进行设计,objective-c,ios8,interface-builder,nsattributedstring,ibdesignable,Objective C,Ios8,Interface Builder,Nsattributedstring,Ibdesignable,我在UIView子类上使用IB_DESIGNABLE,因为我希望能够以编程方式生成属性字符串,但让它出现在Interface builder中,这样我就不用运行应用程序来查看格式了 有人告诉我,我可以把我的代码放入 - (void)prepareForInterfaceBuilder; 它在一定程度上起作用。它出现在界面生成器中。但是,当我运行应用程序时,格式就丢失了。它仍然会出现在界面生成器中,但不会出现在应用程序中 下面是我尝试使用的创建属性字符串的方法,但它们不会出现在interface
- (void)prepareForInterfaceBuilder;
它在一定程度上起作用。它出现在界面生成器中。但是,当我运行应用程序时,格式就丢失了。它仍然会出现在界面生成器中,但不会出现在应用程序中
下面是我尝试使用的创建属性字符串的方法,但它们不会出现在interface builder中,也不会在应用程序运行时出现
- (instancetype)initWithFrame:(CGRect)frame;
- (void)drawRect:(CGRect)frame;
尽管如此,我还是找到了一种方法,可以在应用程序中呈现,但不能在interface builder中呈现
- (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
你问题中的解决方案运行正常,但原因是错误的。您要做的是从initWithCoder:和initWithFrame:调用配置方法LocalizeAttributeString,如下所示 PrepareForenterFaceBuilder是一种特殊方法,仅在呈现IB_可设计视图的上下文中调用。例如,如果自定义视图通常从web服务获取部分数据,则在PrepareForenterFaceBuilder中,您只需提供示例数据即可
@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