Reputation: 2224
I am trying to change the font size of an NSAttributedString dynamically. The problem is the string contains different font sizes and properties. so when i change the font size all the content size change to tat value. Not changing accordingly . .. . .
Upvotes: 0
Views: 1256
Reputation: 6385
If I understood you correctly this approach should help you: you can enumerate all NSFontAttributeName
attributes for your AttributedString
and increase the font size by for instance 1. This would give you the following result:
If that's what you want here is the code to achieve this
- (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;
}
Upvotes: 7