Changing font size of an NSAttributedString

Guides | Tutorial By 4 years ago

An attributed string is a way of storing a piece of text with styling. Similar to the way html works, it can specify certain styles for bits and pieces of the text. They are pretty simple to work with if you’re adding new attributes. If you are changing attributes then things can get a bit trickier as your existing attributes may be overwritten.

In a project I’m currently working on I need to specify a font size but keep all the current styling, font family, colours, and any other attributes.

I’ve created an NSAttributedString category for this, which many may find useful. This involves going through each attribute and making changes individually.

[attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {

}];

Here’s the final implementation:

NSAttributedString+FontSize.h

@interface NSAttributedString (FontSize)

- (NSAttributedString*) attributedStringWithFontSize:(CGFloat) fontSize;

@end

NSAttributedString+FontSize.m

#import "NSAttributedString+FontSize.h"

@implementation NSAttributedString (FontSize)

- (NSAttributedString*) attributedStringWithFontSize:(CGFloat) fontSize
{
	NSMutableAttributedString* attributedString = [self mutableCopy];

	{
		[attributedString beginEditing];

		[attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {

			UIFont* font = value;
			font = [font fontWithSize:fontSize];

			[attributedString removeAttribute:NSFontAttributeName range:range];
			[attributedString addAttribute:NSFontAttributeName value:font range:range];
		}];

		[attributedString endEditing];
	}

	return [attributedString copy];
}

@end
  • Evan Buxton

    Nice work. I was looking for something like this.

  • Vladislav Dzhidzhoev

    Thank you very much! You helped me.