Using NSRegularExpression with NSAttributedString

No comments on Using NSRegularExpression with NSAttributedString

Written by

in

I think, it is a very convenient way to use regular expressions to find a range for applying attributes to NSAttributedString. This is how I did it:

    NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText];

    NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
    if (range.location != NSNotFound) {
        [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range];
        [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
    }

    NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]];
    range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
    if (range.location != NSNotFound) {
        [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range];
        [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    }

    [self.textView setAttributedText:goodText];

I was searching for a list of available attributes and didn’t find them in a class reference’s first page. So I decided to post here information on that.

Attributed strings support the following standard attributes for text.

    NSString *NSFontAttributeName;
    NSString *NSParagraphStyleAttributeName;
    NSString *NSForegroundColorAttributeName;
    NSString *NSUnderlineStyleAttributeName;
    NSString *NSSuperscriptAttributeName;
    NSString *NSBackgroundColorAttributeName;
    NSString *NSAttachmentAttributeName;
    NSString *NSLigatureAttributeName;
    NSString *NSBaselineOffsetAttributeName;
    NSString *NSKernAttributeName;
    NSString *NSLinkAttributeName;
    NSString *NSStrokeWidthAttributeName;
    NSString *NSStrokeColorAttributeName;
    NSString *NSUnderlineColorAttributeName;
    NSString *NSStrikethroughStyleAttributeName;
    NSString *NSStrikethroughColorAttributeName;
    NSString *NSShadowAttributeName;
    NSString *NSObliquenessAttributeName;
    NSString *NSExpansionAttributeName;
    NSString *NSCursorAttributeName;
    NSString *NSToolTipAttributeName;
    NSString *NSMarkedClauseSegmentAttributeName;
    NSString *NSWritingDirectionAttributeName;
    NSString *NSVerticalGlyphFormAttributeName;
    NSString *NSTextAlternativesAttributeName;

Standart Attributes

NSAttributedString programming guide

A full class reference is here

 

Comments

Leave a Reply

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