From the blog

NSAttributedString Creation Helpers

NSAttributedString is a great addition to the iOS SDK.

Since the release of iOS 6, we are able to use NSAttributedString with UIKit, assigning it to UILabels and UITextViews. Here is the code for creating this NSAttributedString: “(middleContent)” (with bold parentheses and italic middle content):

NSDictionary *italicAttrs = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Italic" size:16], NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5f alpha:1.0f]};

NSDictionary *defaultAttrs = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Medium" size:16], NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5f alpha:1.0f]};

NSMutableAttributedString *labelText = [[NSMutableAttributedString alloc] init];

NSAttributedString *open = [[NSAttributedString alloc] initWithString:@"("
                                                           attributes:defaultAttrs];

NSAttributedString *content = [[NSAttributedString alloc] initWithString:@"middleContent"]
                                                              attributes:italicAttrs];

NSAttributedString *close = [[NSAttributedString alloc] initWithString:@")"
                                                            attributes:defaultAttrs];

[labelText appendAttributedString:open];
[labelText appendAttributedString:content];
[labelText appendAttributedString:close];

self.label.attributedText = labelText;

The above example shows that an abundance of code is required to create a very basic string. The inefficiency of Apple’s interface for NSAttributedString leaves a lot to be desired.

Following a similar syntax as NSDictionary’s – (instancetype)initWithObjectsAndKeys:(id)firstObject … we can simplify this creation.

NSDictionary *italicAttrs = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Italic" size:16], NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5f alpha:1.0f]};

NSDictionary *defaultAttrs = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Medium" size:16], NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5f alpha:1.0f]};

NSAttributedString *labelText = [NSAttributedString rz_attributedStringWithStringsAndAttributes:@"(", defaultAttrs, @"middleContent", italicAttrs, @")", defaultAttrs];

self.label.attributedText = labelText;

Read more about the above category for NSAttributedString on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *