b2cloud

27th September 2013

Changing font size of an NSAttributedString

Guides | Tutorial By 3 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.

Recommended Posts

Yammer integrations in ReactJS

Post by 3 years ago

I am writing this blog while I am working on a project for our client’s intranet website. The client requires the website has the ability to share, like and write comments in the website through

Got an idea?

We help entrepreneurs, organizations and established brands from around
the country bring ideas to life. We would love to hear from you!