我正在尝试动态更改NSAttributedString的字体大小。问题是字符串包含不同的字体大小和属性。因此,当我更改字体大小时,所有内容大小都会更改为tat值。没有相应改变。 .. 。
答案 0 :(得分:7)
如果我理解正确,这种方法可以帮助您:您可以枚举NSFontAttributeName
的所有AttributedString
属性,并通过例如1增加字体大小。这会给您以下结果:< / p>
如果这就是你想要的,那就是实现这个目标的代码
- (void)viewDidLoad
{
[super viewDidLoad];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0., 0., 320., 320.)];
self.label.textAlignment = NSTextAlignmentCenter;
self.label.backgroundColor = [UIColor whiteColor];
self.label.numberOfLines = 0.;
NSString *text = @"Small medium large";
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
[attributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, 6)];
[attributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(6, 7)];
[attributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(13, 5)];
self.label.attributedText = attributedText;
[self.view addSubview:self.label];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(bumpFontSize) userInfo:nil repeats:YES];
}
- (void)bumpFontSize
{
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.label.attributedText];
[self.label.attributedText enumerateAttributesInRange:NSMakeRange(0., self.label.text.length) options:NSAttributedStringEnumerationReverse usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop)
{
NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
UIFont *font = mutableAttributes[NSFontAttributeName];
UIFontDescriptor *fontProperties = font.fontDescriptor;
NSNumber *sizeNumber = fontProperties.fontAttributes[UIFontDescriptorSizeAttribute];
[attributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize: [sizeNumber floatValue] + 1.] range:range];
}];
self.label.attributedText = attributedText;
}