How to increase the font size of a NSAttributedsString in iOS

醉酒当歌 提交于 2019-12-25 04:23:05

问题


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 . .. . .


回答1:


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;
}


来源:https://stackoverflow.com/questions/22450669/how-to-increase-the-font-size-of-a-nsattributedsstring-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!